Lab Six: Convolutional Network Architectures

BY Yifan Ding

Business Understanding

Overview

This dataset is collected from Guangzhou Women and Children’s Medical Center, Guangzhou, and consists of X-ray images of children age 1-5, some of whom had bacterial or viral pneumonia. The images are x-rays of the chest and have been labeled by two different doctors---with a third the tiebreaker if the two disagreed. The original images are in different size, so we resized each image to 160x240 pixels jpeg and converted them into grayscale images. The following graph is from the last page from the Cell Paper: "Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning" shows the distinction between a normal lung, a lung with bacterial pneumonia, and a lung with viral pneumonia. https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia![image.png](attachment:image.png)

In [1]:
from IPython.display import Image
Image(filename = "/Users/xuechenli/Downloads/lessons/7324/lab2/Lung_Classification.png" )
Out[1]:

Purpose

The purpose of this dataset was to develop an artificial neural network that will be able to distinguish between children with pneumonia in order to assist doctors in making the right decision. There are three different classifications: normal, pneumonia-bacterial, and pneumonia-viral. The cell paper, "Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning"'s focus is to use transfer learning which is a technique to train a neural network with a relatively small number of images, (Kermany 1122). For us, our purpose will be to classify the aforementioned three types for a preliminary screening. As such, the kids will still receive medial care and a second opinion from a doctor so the stakes are not quite as high for our algorithm.

Prediction Task

There are three different classifications for our image data. The prediction task for this algorithm is to distinguish between children with a normal lung, a lung with bacterial pneumonia, and a lung with viral pneumonia. This algorithm would be used by hospitals who have an x-ray machine and who serve children between the ages of 1-5. Though this data was screened by Chinese children, it can probably be used for children of other nationalities as well.

Importance

According to the Cell Paper, data collected by the World Health organization shows that pneumonia kills approximately 2 million children under 5 years old every year (though most of these deaths occur in Southeast asia or Africa). (Kermany 1127) Since chest x-rays are common and can be used to identify between kids with pneumonia and kids without pneumonia, x-rays were chosen as the method of choice. If we could develop an accurate and quick classifier, it might be able to be used wherever x-rays are used. If developed, such an algorithm could be used by nurses and would not require a doctor to analyze the chest x-ray images. This technique would just save Doctors' time and, potentially, the children who are suffering from pneumonia. Th algorithm would successfully screen kids with pneumonia and direct them to the needed medical care: antibiotics if the child had bacterial pneumonia, supportive care if the child had viral pneumonia, and discharge if the child does not have pneumonia.

Desired Accuracy of Classifier

In order for our algorithm to be useful, it would have to be better than the neural net algorithm that has already been created using the same data in some way. This could mean that our algorithm achieves a greater accuracy than their 93 % and that the area under the ROC curve for our algorithm is better than the area under the ROC curve, (Kermany 1127). The ROC curve is a way to measure the performance of the algorithm by graphing the true positive rate vs. the false positive rate. The higher to the left the algorithm line is the better the algorithm is. The algorithm in the paper achieved the following ROC curve:

In [129]:
Image(filename = "/Users/xuechenli/Downloads/lessons/7324/lab2/ROC_Curve.png" )
Out[129]:

False Positive vs False Negative Trade-off

In all classification problems, it is important to consider which is worse: false positives or false negatives. In this case, we will define a false positive as when the algorithm predicts that a child has pneumonia even when he or she doesn’t. A false negative is when the classifier predicts that the child does not have pneumonia even when the child does. In this case, it is clear that we want to limit the amount of false negatives and instead have more false positives. If there is a false positive, all that will happen is that the child will go under more supervised care—if the child does not have pneumonia, this will probably be found with time. If there is a false negative, though, the child will potentially leave the hospital even though he or she has pneumonia. Clearly, we will try to have more false positives than false negatives in this case.

Citation for Business Understanding

Kermany, D., Goldbaum, M., Cai, W., Valentim, C., Liang, H., Baxter, S., McKeown, A., Yang, G., Wu, X., Yan, F., Dong, J., Prasadha, M., Pei, J., Ting, M., Zhu, J., Li, C., Hewett, S., Dong, J., Ziyar, I., Shi, A., Zhang, R., Zheng, L., Hou, R., Shi, W., Fu, X., Duan, Y., Huu, V., Wen, C., Zhang, E., Zhang, C., Li, O., Wang, X., Singer, M., Sun, X., Xu, J., Tafreshi, A., Lewis, M., Xia, H. and Zhang, K. (2018). Identifying Medical Diagnoses and Treatable Diseases by Image-Based Deep Learning. Cell, 172(5), pp.1122-1131.e9.

Kaggle Dataset: https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia

Data Preparation

Import required modules

In [260]:
#!pip install opencv-python
# Step 1: Import Modules
import numpy as np
import pandas as pd
import os, sys
import cv2 
from tqdm import tqdm 
import skimage
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import sys
import time
import gc
import math

from os import listdir
from glob import glob
import cv2
import seaborn as sns

import keras
from keras.regularizers import l2
from keras.wrappers.scikit_learn import KerasClassifier
import keras.backend as K
from keras.callbacks import EarlyStopping,Callback,ModelCheckpoint
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.preprocessing.image import img_to_array, load_img, ImageDataGenerator
from keras.utils.np_utils import to_categorical

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline

import plotly
plotly.offline.init_notebook_mode()

from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, precision_score
from sklearn import metrics as mt
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier

print('Python:', sys.version)
print('Pandas:', pd.__version__)
print('Numpy:', np.__version__)
print('keras:', keras.__version__)
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
Python: 3.7.3 (default, Mar 27 2019, 16:54:48) 
[Clang 4.0.1 (tags/RELEASE_401/final)]
Pandas: 0.24.2
Numpy: 1.16.4
keras: 2.3.1
In [ ]:
w,h=80,120

Read image data from folder

In [2]:
folder1 = "/Users/yifan/Desktop/train/NORMAL/"
normal = [f for f in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, f))]
folder2 = "/Users/yifan/Desktop/train/PNEUMONIA/"
pneumonia = [f for f in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, f))]
folder = "/Users/yifan/Desktop/train/"
chest = normal + pneumonia
print("Working with {0} images".format(len(chest)))
Working with 5216 images

Pre-processing images

In [3]:
#Code from https://github.com/deadskull7/Pneumonia-Diagnosis-using-XRays-96-percent-Recall/blob/master/Pneumonia%20Diagnosis%20using%20Lung's%20XRay%20.ipynb

def read_data(folder):
    images = []
    labels = [] #Ture status
    for dirc in os.listdir(folder):
        readin = folder + dirc
        if not dirc.startswith('.'):
            if dirc in ['NORMAL']:
                for image_name in tqdm(os.listdir(readin)):
                    label = 0
                    labels.append(label)
            elif dirc in ['PNEUMONIA']: 
                for image_name in tqdm(os.listdir(readin)):
                    if 'bacteria' in str(image_name):         
                        label = 1
                    elif 'virus' in str(image_name):
                        label = 2
                    labels.append(label)

            for image_name in tqdm(os.listdir(readin)):
                img = cv2.imread(readin + '/' + image_name) #Read in images from folder
                if img is not None:
                    img = skimage.transform.resize(img, (w,h,3)) #Resize each image into 160*240
                    img = np.asarray(img) #Turn each image into array
                    img = ((img/255.)-.5) * 2  #Standardization
                    images.append(img)
                    
            
    images = np.asarray(images) 
    labels = np.asarray(labels)
    
    return images,labels
In [4]:
chest_images, chest_ture = read_data(folder)
100%|██████████| 3875/3875 [00:00<00:00, 1548782.92it/s]
100%|██████████| 3875/3875 [10:17<00:00,  5.07it/s]
100%|██████████| 1341/1341 [00:00<00:00, 2223146.90it/s]
100%|██████████| 1341/1341 [11:30<00:00,  2.11it/s]
In [5]:
print(chest_images.shape)
print(chest_ture.shape)
(5216, 80, 120, 3)
(5216,)
In [6]:
print(chest_ture)
[1 1 1 ... 0 0 0]
In [7]:
chest_labels=[]
for label in chest_ture:
    if label == 0:
        chest_labels.append('normal')
    elif label == 1:
        chest_labels.append('bacteria')
    else:
        chest_labels.append('virus')

Convert to Gray Scale

Luminance is by far more important in distinguishing visual features. An excellent suggestion to illustrate this property would be: take a given image and separate the luminance plane from the chrominance planes. We will use 0.3R+0.59G+0.11*B to convert all the images into gray sclae. Range of grayscale values should spread out between 0 and 255.

In [8]:
def gray_scale(data):
    '''
    input: a np.array of images of rgb format
    output: a np.array of images of grayscale format
    '''
    n_images = data.shape[0]
    n_rows = data.shape[1]
    n_columns = data.shape[2]
    grayscale = np.zeros((n_images, n_rows, n_columns, 1))
    
    for idx in range(n_images):
        grayscale[idx, :, :, 0] = np.add(0.3*data[idx,:,:,0], 0.59*data[idx,:,:,1],
                                        0.2*data[idx,:,:,2])
    return grayscale  
In [9]:
chest_gray = gray_scale(chest_images)
In [10]:
print(chest_gray.shape)
(5216, 80, 120, 1)

Linearize the Data

In [11]:
def linearize(data):
    '''
    input:a np.array of images
    output: a 2-D np.array(1-D image feature for each row)
    '''
    num_images = data.shape[0]
    num_columns = int(np.prod(data.shape)/num_images)
    
    linear = np.zeros((num_images, num_columns))
    linear = np.reshape(data, (num_images, num_columns))
    return linear

chest_gray_linear = linearize(chest_gray)
chest_rgb_linear = linearize(chest_images)
In [12]:
print(chest_gray_linear.shape)
(5216, 9600)

Images examples

We displayed some images from three groups.

In [13]:
%matplotlib inline
plt.style.use('ggplot')

# a helper plotting function
def plot_gallery(images, titles, h,w, n_row=3, n_col=6):
    """Helper function to plot a gallery of portraits"""
    plt.figure(figsize=(1.7 * n_col, 2.3 * n_row))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())
        
plot_gallery(chest_gray, chest_labels,w,h)

From the images of normal chest and pneumonia, we can hardly tell the differences between them just by insight. It indicates that further analysis of images is essential for this case.

In [14]:
i=0
j=0
k=0
for label in chest_ture:
    if label == 1:
        i=i+1
    elif label == 2:
        j=j+1
    else:
        k=k+1
print('bacteria:',i,
      'virus:',j,
     'normal:',k)
bacteria: 2530 virus: 1345 normal: 1341

Description of Final Dataset

Each column in dataset represents a specific pixel, each row represents one image,which is total 5216 images. A value in dataset represents the darkness or grayscale of the image. Our target is 3 classes outuput, normal, bacteria and virus.

Data Reduction

Principal Component Analysis (PCA)

PCA Equations

Raschka, S. and Mirjalili, V. (n.d.). Python Machine Learning: Machine Learning and Deep Learning with Python, scikit-learn, and TensorFlow. 2nd ed. Packt Publishing.

Feature Reduction:

$$x = \begin{bmatrix} x_{1} & x_{2} & ... & x_{d} \end{bmatrix}, x \, \epsilon \, \mathbb{R}^{d}$$$$\downarrow xW, W\epsilon \, \mathbb{R}^{dxk}$$$$z = \begin{bmatrix} z_{1} &z_{2} & ... & z_{k} \end{bmatrix}, z\, \epsilon \, \mathbb{R}^{k}$$

Creating the Covariance Matrix (pg 145-pg 146 in Raschka)

$$\sigma _{jk} = \frac{1}{n}\sum_{i = 1}^{n} (x^{(i)}_{j} -\mu _{j})(x_{k}^{(i)} -\mu _{k})$$$$ \sum = \begin{bmatrix} \sigma ^{2}_{1} & \sigma _{12} & \sigma _{13} \\ \sigma _{21}& \sigma ^{2}_{2} & \sigma _{23}\\ \sigma _{31}& \sigma _{32} & \sigma ^{2}_{3} \end{bmatrix} $$

Find Eigenvalues (pg 146 in Raschka)

$$\varepsilon v = \lambda v$$

Total and Explained Variance (pg 147 in Raschka)

$$\frac{\lambda _{j}}{\sum_{j=1}^{d} \lambda _{j}}$$

Projecting onto new Feature Space (page 162 in Raschka)

$$X^{'} = XW$$
In [15]:
from sklearn.decomposition import PCA
import seaborn as sns
from sklearn.decomposition import IncrementalPCA
from sklearn.decomposition import KernelPCA
from sklearn.decomposition import SparsePCA
In [16]:
def full_pca(data,n):
    '''
    input:data,n_components
    output: full pca of data
    '''
    chest_pca = PCA(n_components=n)
    return chest_pca.fit(chest_gray_linear)
In [17]:
chest_pca = full_pca(chest_gray_linear,5216)

Plot individual and cumulative explained variance

In [25]:
def explain_variance(pca):
    '''
    input:pca 
    output: explained variance
    '''
    explained_var = pca.explained_variance_ratio_
    return explained_var
In [20]:
def cumu_variance(pca):
    '''
    input:pca 
    output: cumulative variance
    '''
    cumu_var_exp = np.cumsum(pca.explained_variance_ratio_)
    return cumu_var_exp
In [21]:
cumu_var = cumu_variance(chest_pca)
explained_var = explain_variance(chest_pca)
print(cumu_var)
print(explained_var)
[0.25632606 0.36139141 0.43453036 ... 1.         1.         1.        ]
[2.56326056e-01 1.05065359e-01 7.31389425e-02 ... 2.46829023e-37
 2.46299002e-37 4.40894729e-38]
In [22]:
#!pip install cufflinks plotly
In [23]:
#The plot_explained_variance function is adapted from Eric's 04. Dimension Reduction and Images

from plotly.graph_objs import Scatter, Marker, Layout, XAxis, YAxis, Bar, Line
import plotly 
def plot_explained_variance(var1,var2):  
    plotly.offline.iplot({
    "data": [Scatter(y=var1, name='Explained variance'),
             Scatter(y=var2, name='cumulative explained variance')
        ],
    "layout": Layout(xaxis=XAxis(title='Principal components'), yaxis=YAxis(title='Explained variance ratio'))
    })
In [24]:
plot_explained_variance(explained_var,cumu_var)
/Users/xuechenli/anaconda3/lib/python3.6/site-packages/plotly/graph_objs/_deprecations.py:550: DeprecationWarning:

plotly.graph_objs.XAxis is deprecated.
Please replace it with one of the following more specific types
  - plotly.graph_objs.layout.XAxis
  - plotly.graph_objs.layout.scene.XAxis


/Users/xuechenli/anaconda3/lib/python3.6/site-packages/plotly/graph_objs/_deprecations.py:578: DeprecationWarning:

plotly.graph_objs.YAxis is deprecated.
Please replace it with one of the following more specific types
  - plotly.graph_objs.layout.YAxis
  - plotly.graph_objs.layout.scene.YAxis


Retaining 40 components will get an explained variance ratio of 0.8 and retaining 200 components will get an explained variance ratio of 0.9. Since 200 is at the knee of the graph, it is appropriate for us to using the first 200 components to represent the chest image.

PCA with first 200 components

In [330]:
chest_pca_first200 = full_pca(chest_gray_linear,200)

Plot individual and cumulative explained variance ( first 200 components)

In [26]:
cumu_var = cumu_variance(chest_pca_first200)
explained_var = explain_variance(chest_pca_first200)
plot_explained_variance(explained_var,cumu_var)
/Users/xuechenli/anaconda3/lib/python3.6/site-packages/plotly/graph_objs/_deprecations.py:550: DeprecationWarning:

plotly.graph_objs.XAxis is deprecated.
Please replace it with one of the following more specific types
  - plotly.graph_objs.layout.XAxis
  - plotly.graph_objs.layout.scene.XAxis


/Users/xuechenli/anaconda3/lib/python3.6/site-packages/plotly/graph_objs/_deprecations.py:578: DeprecationWarning:

plotly.graph_objs.YAxis is deprecated.
Please replace it with one of the following more specific types
  - plotly.graph_objs.layout.YAxis
  - plotly.graph_objs.layout.scene.YAxis


Reshape with first 200 components

In [338]:
eigen_chest = chest_pca_first200.components_.reshape(200,w,h)
In [339]:
eigen_chest.shape
Out[339]:
(200, 80, 120)
In [340]:
#The plot_gallery function is from Eric's 04. Dimension Reduction and Images

import matplotlib.pyplot as plt# a helper plotting function
def plot_gallery(images, titles, h, w, n_row=4, n_col=6):
    """
    input:  image matrix
    output: image gallery 
    """
    plt.figure(figsize=(1.7 * n_col, 2.3 * n_row))
    plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35)
    for i in range(n_row * n_col):
        plt.subplot(n_row, n_col, i + 1)
        plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray)
        plt.title(titles[i], size=12)
        plt.xticks(())
        plt.yticks(())
In [341]:
eigenlabels = ['eigenimage ' + str(i) for i in range(eigen_chest.shape[0])]
plot_gallery(eigen_chest,eigenlabels,w,h)

The components represent our images well. The first component reflect the average of the 5216 images

Compare Original with PCA

In [31]:
#Reconstruct_image function is adapated from Eric's 04 Dimensional Reduction and Images
''' original from Eric
def reconstruct_image(trans_obj,org_features):
    low_rep = trans_obj.transform(org_features)
    rec_image = trans_obj.inverse_transform(low_rep)
    return low_rep, rec_image
    
idx_to_reconstruct = 131    
chest_gray_linear_idx = chest_gray_linear[idx_to_reconstruct]
low_dim, reconstructed_image = reconstruct_image(chest_pca_first200,chest_gray_linear_idx.reshape(1, -1))
'''
def reconstruct_image(trans_obj,pca_features,idx):
    '''
    input:pca_data,trans_obj,org_features,idx
    output:tranformation of the specific picture
    '''
    low_dim = trans_obj.transform(pca_features[idx].reshape(1,-1))
    rec_image = trans_obj.inverse_transform(low_dim)
    return low_dim, rec_image
In [32]:
chest_gray_linear.shape
Out[32]:
(5216, 38400)
In [342]:
chest_pca_first200.components_.shape
Out[342]:
(200, 9600)
In [34]:
#Make a comparison here
#Take the 100th image as an example
low_dim, rec_image = reconstruct_image(chest_pca_first200,chest_gray_linear,100)

plt.subplot(1,2,1)
plt.imshow(chest_gray_linear[100].reshape(160,240), cmap=plt.cm.gray)
plt.title('Original')
plt.grid(False)

plt.subplot(1,2,2)
plt.imshow(rec_image.reshape(160,240), cmap=plt.cm.gray)
plt.title('full component PCA')
plt.grid(False)

As a check on our code, we tried to calculate Radial Based PCA as a negative case to see whether it is the worst one among those PCA methods. From the image analysis, we expect it to be the worst. Thankfully, it only has an accuracy of 72%.

New for lab6

So comparing PCA and Kernal PCA with the first 200 components, it is clear that the PCA and polynomial PCA do the best with more than 95% accuracy, while the Radial Based PCA does the worst, with only 75% accuarcy.

Above all, we would use the full PCA with first 200 components to be the final dataset that is used for classification.

Split train and test data set

Use Stratified 10-fold to separate train and test set

In [28]:
# Data to plot
labels = 'bacteria','virus','normal'
sizes = [2530,1345,1341]
colors = ['gold', 'yellowgreen', 'lightcoral']

# Plot
plt.pie(sizes,labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)

plt.show()

As you can see above, we have 1341 samples that are normal, 2530 samples that are pneumonia-bacteria and 1345 samples that are pneumonia-viral, the proportion are quite different for three classes. So we want to keep the same proportion of different classes in each fold to make sure that each fold is a good representative of the whole data. Another problem we have to pay attention to is our sample size. From the counts of three categories, the sample size for normal and pneumonia-viral is small. After we do a 80/20 split for train and test set, we only have 1341/5=268 samples of normal in the test set. It is not enough, and we can get almost any performance on this set only due to chance. In K Fold cross validation, the data is divided into k subsets.

Now the holdout method is repeated k times, such that each time, one of the k subsets is used as the test set/ validation set and the other k-1 subsets are put together to form a training set. The error estimation is averaged over all k trials to get total effectiveness of our model. As can be seen, every data point gets to be in a validation set exactly once, and gets to be in a training set k-1 times. This significantly reduces bias as we are using most of the data for fitting, and also significantly reduces variance as most of the data is also being used in validation set. As a general rule and empirical evidence, K = 5 or 10 is generally preferred as it is often reported that the optimal k is between 5 and 10 , because the statistical performance does not increase a lot for larger values of k. So for our problem, using a 5/10 fold cross validation method to do an 80/20 split is a better way. Since we also want the same proportion of different classes in each fold, Stratified 10-fold is a better choice.

Reference

Arlot, Sylvain, and Alain Celisse. “A Survey of Cross-Validation Procedures for Model Selection.” Statistics Surveys, The Author, under a Creative Commons Attribution License, https://projecteuclid.org/download/pdfview_1/euclid.ssu/1268143839.

Gupta, Prashant. “Cross-Validation in Machine Learning.” Medium, Towards Data Science, 5 June 2017, https://towardsdatascience.com/cross-validation-in-machine-learning-72924a69872f.

Shulga, Dima. “5 Reasons Why You Should Use Cross-Validation in Your Data Science Projects.” Medium, Towards Data Science, 27 Sept. 2018, https://towardsdatascience.com/5-reasons-why-you-should-use-cross-validation-in-your-data-science-project-8163311a1e79.

Use sklearn StratifiedKFold to implement

We use our method to evaluate the metric by 10-fold Stratified Cross Validation.

In [407]:
from sklearn.model_selection import StratifiedKFold,cross_val_score
from sklearn import metrics

chest_skf=StratifiedKFold(n_splits=10)
X_train = []
X_test = []
y_train = []
y_test = []

for train_index,test_index in chest_skf.split(chest_gray_linear,chest_ture):
    print("Train Index:",train_index,",Test Index:",test_index)
    X_train_temp, X_test_temp =chest_gray_linear[train_index],chest_gray_linear[test_index]
    y_train_temp ,y_test_temp =chest_ture[train_index],chest_ture[test_index]
    
    X_train.append(X_train_temp)
    X_test.append(X_test_temp)
    y_train.append(y_train_temp)
    y_test.append(y_test_temp)
Train Index: [ 373  378  381 ... 5213 5214 5215] ,Test Index: [   0    1    2    3    4    5    6    7    8    9   10   11   12   13
   14   15   16   17   18   19   20   21   22   23   24   25   26   27
   28   29   30   31   32   33   34   35   36   37   38   39   40   41
   42   43   44   45   46   47   48   49   50   51   52   53   54   55
   56   57   58   59   60   61   62   63   64   65   66   67   68   69
   70   71   72   73   74   75   76   77   78   79   80   81   82   83
   84   85   86   87   88   89   90   91   92   93   94   95   96   97
   98   99  100  101  102  103  104  105  106  107  108  109  110  111
  112  113  114  115  116  117  118  119  120  121  122  123  124  125
  126  127  128  129  130  131  132  133  134  135  136  137  138  139
  140  141  142  143  144  145  146  147  148  149  150  151  152  153
  154  155  156  157  158  159  160  161  162  163  164  165  166  167
  168  169  170  171  172  173  174  175  176  177  178  179  180  181
  182  183  184  185  186  187  188  189  190  191  192  193  194  195
  196  197  198  199  200  201  202  203  204  205  206  207  208  209
  210  211  212  213  214  215  216  217  218  219  220  221  222  223
  224  225  226  227  228  229  230  231  232  233  234  235  236  237
  238  239  240  241  242  243  244  245  246  247  248  249  250  251
  252  253  254  255  256  257  258  259  260  261  262  263  264  265
  266  267  268  269  270  271  272  273  274  275  276  277  278  279
  280  281  282  283  284  285  286  287  288  289  290  291  292  293
  294  295  296  297  298  299  300  301  302  303  304  305  306  307
  308  309  310  311  312  313  314  315  316  317  318  319  320  321
  322  323  324  325  326  327  328  329  330  331  332  333  334  335
  336  337  338  339  340  341  342  343  344  345  346  347  348  349
  350  351  352  353  354  355  356  357  358  359  360  361  362  363
  364  365  366  367  368  369  370  371  372  374  375  376  377  379
  380  382  386  392  393  394  395  397  398  402 3875 3876 3877 3878
 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892
 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920
 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976
 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990
 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
 4005 4006 4007 4008 4009]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [ 373  378  381  383  384  385  387  388  389  390  391  396  399  400
  401  403  404  405  406  407  408  409  410  411  412  413  414  415
  416  417  418  419  420  421  422  423  424  425  426  427  428  429
  430  431  432  433  434  435  436  437  438  439  440  441  442  443
  444  445  446  447  448  449  450  451  452  453  454  455  456  457
  458  459  460  461  462  463  464  465  466  467  468  469  470  471
  472  473  474  475  476  477  478  479  480  481  482  483  484  485
  486  487  488  489  490  491  492  493  494  495  496  497  498  499
  500  501  502  503  504  505  506  507  508  509  510  511  512  513
  514  515  516  517  518  519  520  521  522  523  524  525  526  527
  528  529  530  531  532  533  534  535  536  537  538  539  540  541
  542  543  544  545  546  547  548  549  550  551  552  553  554  555
  556  557  558  559  560  561  562  563  564  565  566  567  568  569
  570  571  572  573  574  575  576  577  578  579  580  581  582  583
  584  585  586  587  588  589  590  591  592  593  594  595  596  597
  598  599  600  601  602  603  604  605  606  607  608  609  610  611
  612  613  614  615  616  617  618  619  620  621  622  623  624  625
  626  627  628  629  630  631  632  633  634  635  636  637  638  639
  640  641  642  643  644  645  646  647  648  649  650  651  652  653
  654  655  656  657  658  659  660  661  662  663  664  665  666  667
  668  669  670  671  672  673  674  675  676  677  678  679  680  681
  682  683  684  685  686  687  688  689  690  691  692  693  694  695
  696  697  698  699  700  701  702  703  704  705  706  707  708  709
  710  711  712  713  714  715  716  717  718  719  720  721  722  723
  724  725  726  727  728  729  730  731  732  733  734  735  736  737
  738  740  743  746  748  749  751  752  754  755  756  757  760  761
  762  763  764  765  766  768  769  770  771  772  773  774  778  780
  781  782  783  784  785  786  787  790  791  793 4010 4011 4012 4013
 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027
 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041
 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069
 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083
 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125
 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
 4140 4141 4142 4143]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [ 739  741  742  744  745  747  750  753  758  759  767  775  776  777
  779  788  789  792  794  795  796  797  798  799  800  801  802  803
  804  805  806  807  808  809  810  811  812  813  814  815  816  817
  818  819  820  821  822  823  824  825  826  827  828  829  830  831
  832  833  834  835  836  837  838  839  840  841  842  843  844  845
  846  847  848  849  850  851  852  853  854  855  856  857  858  859
  860  861  862  863  864  865  866  867  868  869  870  871  872  873
  874  875  876  877  878  879  880  881  882  883  884  885  886  887
  888  889  890  891  892  893  894  895  896  897  898  899  900  901
  902  903  904  905  906  907  908  909  910  911  912  913  914  915
  916  917  918  919  920  921  922  923  924  925  926  927  928  929
  930  931  932  933  934  935  936  937  938  939  940  941  942  943
  944  945  946  947  948  949  950  951  952  953  954  955  956  957
  958  959  960  961  962  963  964  965  966  967  968  969  970  971
  972  973  974  975  976  977  978  979  980  981  982  983  984  985
  986  987  988  989  990  991  992  993  994  995  996  997  998  999
 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 4144 4145 4146 4147
 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161
 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189
 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203
 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217
 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231
 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245
 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259
 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273
 4274 4275 4276 4277]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
 1528 1533 1534 1536 1537 1539 1545 1546 1547 1550 1553 1561 1566 1568
 1572 1577 1589 1590 1594 1595 1598 1600 1602 1603 4278 4279 4280 4281
 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295
 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309
 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337
 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351
 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365
 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379
 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393
 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407
 4408 4409 4410 4411]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [1529 1530 1531 1532 1535 1538 1540 1541 1542 1543 1544 1548 1549 1551
 1552 1554 1555 1556 1557 1558 1559 1560 1562 1563 1564 1565 1567 1569
 1570 1571 1573 1574 1575 1576 1578 1579 1580 1581 1582 1583 1584 1585
 1586 1587 1588 1591 1592 1593 1596 1597 1599 1601 1604 1605 1606 1607
 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
 1916 1917 1918 1923 1925 1927 1929 1931 1936 1939 1941 1944 1945 1946
 1947 1952 1957 1958 1960 1975 1978 1981 1986 1987 4412 4413 4414 4415
 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429
 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457
 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471
 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485
 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513
 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541
 4542 4543 4544 4545]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [1919 1920 1921 1922 1924 1926 1928 1930 1932 1933 1934 1935 1937 1938
 1940 1942 1943 1948 1949 1950 1951 1953 1954 1955 1956 1959 1961 1962
 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1976 1977
 1979 1980 1982 1983 1984 1985 1988 1989 1990 1991 1992 1993 1994 1995
 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2301 2302 2303 2307
 2308 2315 2318 2321 2322 2324 2326 2327 2334 2337 2341 2344 2346 2352
 2354 2364 2371 2377 2381 2386 2388 2391 2395 4546 4547 4548 4549 4550
 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564
 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592
 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606
 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620
 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648
 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662
 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676
 4677 4678 4679]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [2300 2304 2305 2306 2309 2310 2311 2312 2313 2314 2316 2317 2319 2320
 2323 2325 2328 2329 2330 2331 2332 2333 2335 2336 2338 2339 2340 2342
 2343 2345 2347 2348 2349 2350 2351 2353 2355 2356 2357 2358 2359 2360
 2361 2362 2363 2365 2366 2367 2368 2369 2370 2372 2373 2374 2375 2376
 2378 2379 2380 2382 2383 2384 2385 2387 2389 2390 2392 2393 2394 2396
 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438
 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2688 2691 2692 2698
 2700 2710 2712 2713 2715 2716 2721 2722 2724 2725 2726 2730 2736 2739
 2745 2746 2750 2753 2754 2756 2760 2761 2764 4680 4681 4682 4683 4684
 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698
 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712
 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726
 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740
 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754
 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768
 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796
 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810
 4811 4812 4813]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [2687 2689 2690 2693 2694 2695 2696 2697 2699 2701 2702 2703 2704 2705
 2706 2707 2708 2709 2711 2714 2717 2718 2719 2720 2723 2727 2728 2729
 2731 2732 2733 2734 2735 2737 2738 2740 2741 2742 2743 2744 2747 2748
 2749 2751 2752 2755 2757 2758 2759 2762 2763 2765 2766 2767 2768 2769
 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839
 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881
 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035
 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
 3064 3065 3066 3067 3068 3069 3070 3074 3077 3079 3080 3082 3085 3086
 3091 3094 3097 3105 3109 3112 3113 3117 3120 3121 3122 3125 3127 3130
 3132 3134 3142 3144 3147 3148 3150 3151 3152 4814 4815 4816 4817 4818
 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832
 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846
 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860
 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902
 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916
 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930
 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944
 4945 4946 4947]
Train Index: [   0    1    2 ... 5213 5214 5215] ,Test Index: [3071 3072 3073 3075 3076 3078 3081 3083 3084 3087 3088 3089 3090 3092
 3093 3095 3096 3098 3099 3100 3101 3102 3103 3104 3106 3107 3108 3110
 3111 3114 3115 3116 3118 3119 3123 3124 3126 3128 3129 3131 3133 3135
 3136 3137 3138 3139 3140 3141 3143 3145 3146 3149 3153 3154 3155 3156
 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296
 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338
 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380
 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422
 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3466 3468 3470 3472
 3474 3475 3478 3480 3481 3483 3484 3485 3490 3491 3493 3494 3495 3499
 3501 3504 3508 3512 3514 3517 3520 3521 3525 4948 4949 4950 4951 4952
 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966
 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994
 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008
 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022
 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036
 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064
 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078
 5079 5080 5081]
Train Index: [   0    1    2 ... 5079 5080 5081] ,Test Index: [3461 3462 3463 3464 3465 3467 3469 3471 3473 3476 3477 3479 3482 3486
 3487 3488 3489 3492 3496 3497 3498 3500 3502 3503 3505 3506 3507 3509
 3510 3511 3513 3515 3516 3518 3519 3522 3523 3524 3526 3527 3528 3529
 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557
 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571
 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585
 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641
 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655
 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669
 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697
 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739
 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753
 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795
 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809
 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837
 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
 3866 3867 3868 3869 3870 3871 3872 3873 3874 5082 5083 5084 5085 5086
 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100
 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114
 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128
 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142
 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156
 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170
 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184
 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198
 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212
 5213 5214 5215]
In [408]:
# scale the numeric, continuous variables
from sklearn.preprocessing import StandardScaler
for i in range(10):
    ss = StandardScaler()
    X_train[i] = ss.fit_transform(X_train[i])
    X_test[i] = ss.transform(X_test[i])
In [409]:
print(X_train[0])
[[-0.67193352 -0.70305958 -0.6893315  ... -0.3521171  -0.32570586
  -0.28708402]
 [ 0.18288938  0.45014579  0.72850566 ... -0.60914556 -0.58795899
  -0.56338469]
 [-0.96624897 -1.04754902 -1.13095292 ... -0.60914556 -0.55517735
  -0.2952707 ]
 ...
 [ 0.19078991  0.2975301   0.39793525 ... -0.60914556 -0.58795899
  -0.56338469]
 [-0.96624897 -1.04754902 -1.13095292 ... -0.60914556 -0.58795899
  -0.56338469]
 [ 1.75414457  0.45750667 -0.01527777 ... -0.60914556 -0.58795899
  -0.56338469]]

Use pca with first 200 components

In [410]:
train_pca_200=[]
test_pca_200=[]
for i in range(10):
    train_temp = full_pca(X_train[i],200)
    eigen_temp = train_temp.components_
    eigen_temp = np.transpose(eigen_temp)
    train_temp = X_train[i] @ eigen_temp
    test_temp = X_test[i] @ eigen_temp
    train_pca_200.append(train_temp)
    test_pca_200.append(test_temp)
In [411]:
for i in range(10):
    print(i+1,train_pca_200[i].shape,test_pca_200[i].shape)
1 (4693, 200) (523, 200)
2 (4694, 200) (522, 200)
3 (4694, 200) (522, 200)
4 (4694, 200) (522, 200)
5 (4694, 200) (522, 200)
6 (4695, 200) (521, 200)
7 (4695, 200) (521, 200)
8 (4695, 200) (521, 200)
9 (4695, 200) (521, 200)
10 (4695, 200) (521, 200)
In [412]:
CLASSES = 3
y_train_ohe=[]
y_test_ohe=[]
for i in range(10):
    y_train[i]=np.array(y_train[i])
    y_test[i]=np.array(y_test[i])
    y_train_temp = keras.utils.to_categorical(y_train[i], CLASSES)
    y_test_temp = keras.utils.to_categorical(y_test[i], CLASSES)
    y_train_ohe.append(y_train_temp)
    y_test_ohe.append(y_test_temp)

Evaluate metric

Metrics measurement

As we mentioned in False Positive vs False Negative Trade-off, in all classification problems, it is important to consider which is worse: false positives or false negatives. In this case, we will define a false positive as when the algorithm predicts that a child has pneumonia even when he or she doesn’t. A false negative is when the classivier predicts that the child does not have pneumonia even when the child does. In this case, it is clear that we want to limit the amount of false negatives. We also want to keep children from unnessary treatment, which will happen in false positive situation.

Since higher recall ratio illustrates lower false negative and we also concer about lower false positive, we should use F1-score as our main metric. F1-score are defined for binary classes. There are two ways to combine it into multiple classes. micro is calculated for the individual TPs, TNs, FPs, FNs of the confusion matrix, which weights each instance equally. macro is calculated as the average scores of the confusion matrix, which weights each class equally to evaluate the overall performance. Since we have an imbalanced instance for each class, we perfer to use F1 weighted macro-average score.

Given the metric for $K^{th}$ classes $X_k$: $$F1_{micro} = \frac {2\times (TP_1 + ... + TP_k) } {2\times (TP1_1 + ... + TP_k) + FP_1 + ... + FP_k + FN_1 + ... + FN_k} $$

$$F1_{macro} = \frac {X_1 + ... + X_k} {k} $$

Add f1_score

Reference

Guglielmocamporese. “Macro F1-Score Keras.” Kaggle, Kaggle, 20 Oct. 2018, https://www.kaggle.com/guglielmocamporese/macro-f1-score-keras.

In [413]:
# modified by https://www.kaggle.com/guglielmocamporese/macro-f1-score-keras
import keras.backend as K
import tensorflow as tf
from tensorflow import math

def f1(y_true, y_pred):
    y_pred = K.round(y_pred)
    tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
    # tn = K.sum(K.cast((1-y_true)*(1-y_pred), 'float'), axis=0)
    fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)
    fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)

    p = tp / (tp + fp + K.epsilon())
    r = tp / (tp + fn + K.epsilon())

    f1 = 2*p*r / (p+r+K.epsilon())
    f1 = tf.where(tf.math.is_nan(f1), tf.zeros_like(f1), f1)
    return K.mean(f1)

3. Modeling

Define MLP model from sklearn

In [414]:
# make a keras MLP
for i in range(10):
    print('fold: '+ str(i+1))
    mlp = Sequential()
    mlp.add( Dense(input_dim=train_pca_200[i].shape[1], units=100, activation='relu') )
    mlp.add( Dense(units=50, activation='relu') )
    mlp.add( Dense(units=50, activation='relu') )
    mlp.add( Dense(CLASSES) )
    mlp.add( Activation('softmax') )

    mlp.compile(loss='categorical_crossentropy',
                  optimizer='rmsprop',
                  metrics=['accuracy',f1])

    mlp_simple = mlp.fit(train_pca_200[i], y_train_ohe[i], 
            batch_size=32, epochs=10, 
            shuffle=True, verbose=1,validation_data=(test_pca_200[i],y_test_ohe[i]))
fold: 1
Train on 4693 samples, validate on 523 samples
Epoch 1/10
4693/4693 [==============================] - 1s 126us/step - loss: 0.8252 - accuracy: 0.6972 - f1: 0.6528 - val_loss: 0.6154 - val_accuracy: 0.7304 - val_f1: 0.4052
Epoch 2/10
4693/4693 [==============================] - 0s 39us/step - loss: 0.4644 - accuracy: 0.8050 - f1: 0.7766 - val_loss: 0.6185 - val_accuracy: 0.7342 - val_f1: 0.3836
Epoch 3/10
4693/4693 [==============================] - 0s 39us/step - loss: 0.3450 - accuracy: 0.8511 - f1: 0.8361 - val_loss: 0.5896 - val_accuracy: 0.7495 - val_f1: 0.4132
Epoch 4/10
4693/4693 [==============================] - 0s 39us/step - loss: 0.2606 - accuracy: 0.9016 - f1: 0.8959 - val_loss: 0.6457 - val_accuracy: 0.7725 - val_f1: 0.4313
Epoch 5/10
4693/4693 [==============================] - 0s 34us/step - loss: 0.1929 - accuracy: 0.9248 - f1: 0.9190 - val_loss: 0.6201 - val_accuracy: 0.7763 - val_f1: 0.4307
Epoch 6/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.1448 - accuracy: 0.9495 - f1: 0.9444 - val_loss: 0.7030 - val_accuracy: 0.7820 - val_f1: 0.4504
Epoch 7/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.1084 - accuracy: 0.9612 - f1: 0.9584 - val_loss: 0.7876 - val_accuracy: 0.7591 - val_f1: 0.4336
Epoch 8/10
4693/4693 [==============================] - 0s 35us/step - loss: 0.0803 - accuracy: 0.9732 - f1: 0.9716 - val_loss: 0.8628 - val_accuracy: 0.7533 - val_f1: 0.4252
Epoch 9/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.0525 - accuracy: 0.9847 - f1: 0.9836 - val_loss: 0.9348 - val_accuracy: 0.7438 - val_f1: 0.4254
Epoch 10/10
4693/4693 [==============================] - 0s 33us/step - loss: 0.0423 - accuracy: 0.9887 - f1: 0.9881 - val_loss: 1.0271 - val_accuracy: 0.7572 - val_f1: 0.4232
fold: 2
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 78us/step - loss: 0.8026 - accuracy: 0.6905 - f1: 0.6513 - val_loss: 0.6833 - val_accuracy: 0.7490 - val_f1: 0.3804
Epoch 2/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.4533 - accuracy: 0.8093 - f1: 0.7863 - val_loss: 0.5528 - val_accuracy: 0.7605 - val_f1: 0.3898
Epoch 3/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.3292 - accuracy: 0.8602 - f1: 0.8463 - val_loss: 0.5830 - val_accuracy: 0.7778 - val_f1: 0.4117
Epoch 4/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.2519 - accuracy: 0.8999 - f1: 0.8884 - val_loss: 0.6143 - val_accuracy: 0.7912 - val_f1: 0.4287
Epoch 5/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.1947 - accuracy: 0.9227 - f1: 0.9169 - val_loss: 0.6347 - val_accuracy: 0.7854 - val_f1: 0.4301
Epoch 6/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.1369 - accuracy: 0.9508 - f1: 0.9479 - val_loss: 0.8275 - val_accuracy: 0.7567 - val_f1: 0.3977
Epoch 7/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.1057 - accuracy: 0.9625 - f1: 0.9581 - val_loss: 0.8068 - val_accuracy: 0.7720 - val_f1: 0.4156
Epoch 8/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0752 - accuracy: 0.9749 - f1: 0.9735 - val_loss: 1.0163 - val_accuracy: 0.7625 - val_f1: 0.4017
Epoch 9/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0534 - accuracy: 0.9855 - f1: 0.9821 - val_loss: 1.0148 - val_accuracy: 0.7490 - val_f1: 0.3975
Epoch 10/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0395 - accuracy: 0.9898 - f1: 0.9890 - val_loss: 1.1906 - val_accuracy: 0.7625 - val_f1: 0.4025
fold: 3
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 78us/step - loss: 0.7804 - accuracy: 0.6971 - f1: 0.6465 - val_loss: 0.5213 - val_accuracy: 0.7663 - val_f1: 0.4235
Epoch 2/10
4694/4694 [==============================] - 0s 38us/step - loss: 0.4514 - accuracy: 0.8072 - f1: 0.7843 - val_loss: 0.4937 - val_accuracy: 0.7912 - val_f1: 0.4521
Epoch 3/10
4694/4694 [==============================] - 0s 38us/step - loss: 0.3394 - accuracy: 0.8541 - f1: 0.8416 - val_loss: 0.5571 - val_accuracy: 0.7586 - val_f1: 0.4123
Epoch 4/10
4694/4694 [==============================] - 0s 40us/step - loss: 0.2675 - accuracy: 0.8888 - f1: 0.8794 - val_loss: 0.5384 - val_accuracy: 0.7893 - val_f1: 0.4586
Epoch 5/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.2027 - accuracy: 0.9259 - f1: 0.9219 - val_loss: 0.5922 - val_accuracy: 0.7893 - val_f1: 0.4547
Epoch 6/10
4694/4694 [==============================] - 0s 40us/step - loss: 0.1448 - accuracy: 0.9472 - f1: 0.9455 - val_loss: 0.6470 - val_accuracy: 0.7586 - val_f1: 0.4437
Epoch 7/10
4694/4694 [==============================] - 0s 39us/step - loss: 0.1080 - accuracy: 0.9651 - f1: 0.9628 - val_loss: 0.7679 - val_accuracy: 0.7663 - val_f1: 0.4397
Epoch 8/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0749 - accuracy: 0.9774 - f1: 0.9757 - val_loss: 0.8615 - val_accuracy: 0.7759 - val_f1: 0.4450
Epoch 9/10
4694/4694 [==============================] - 0s 37us/step - loss: 0.0541 - accuracy: 0.9855 - f1: 0.9840 - val_loss: 0.9468 - val_accuracy: 0.7854 - val_f1: 0.4484
Epoch 10/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.0443 - accuracy: 0.9883 - f1: 0.9879 - val_loss: 0.9691 - val_accuracy: 0.7759 - val_f1: 0.4485
fold: 4
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 83us/step - loss: 0.7971 - accuracy: 0.6956 - f1: 0.6507 - val_loss: 0.6748 - val_accuracy: 0.7241 - val_f1: 0.3908
Epoch 2/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.4469 - accuracy: 0.8117 - f1: 0.7887 - val_loss: 0.6074 - val_accuracy: 0.7452 - val_f1: 0.4027
Epoch 3/10
4694/4694 [==============================] - 0s 39us/step - loss: 0.3356 - accuracy: 0.8568 - f1: 0.8454 - val_loss: 0.6348 - val_accuracy: 0.7510 - val_f1: 0.4108
Epoch 4/10
4694/4694 [==============================] - 0s 41us/step - loss: 0.2504 - accuracy: 0.8986 - f1: 0.8902 - val_loss: 0.6807 - val_accuracy: 0.7471 - val_f1: 0.4025
Epoch 5/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.1864 - accuracy: 0.9286 - f1: 0.9234 - val_loss: 0.7507 - val_accuracy: 0.7318 - val_f1: 0.4014
Epoch 6/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.1390 - accuracy: 0.9499 - f1: 0.9461 - val_loss: 0.8060 - val_accuracy: 0.7663 - val_f1: 0.4104
Epoch 7/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.1006 - accuracy: 0.9685 - f1: 0.9671 - val_loss: 0.8511 - val_accuracy: 0.7471 - val_f1: 0.4013
Epoch 8/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0684 - accuracy: 0.9776 - f1: 0.9770 - val_loss: 0.9528 - val_accuracy: 0.7356 - val_f1: 0.4043
Epoch 9/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.0460 - accuracy: 0.9868 - f1: 0.9868 - val_loss: 1.1586 - val_accuracy: 0.7241 - val_f1: 0.3919
Epoch 10/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.0368 - accuracy: 0.9896 - f1: 0.9888 - val_loss: 1.1968 - val_accuracy: 0.7739 - val_f1: 0.4238
fold: 5
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 75us/step - loss: 0.7686 - accuracy: 0.6879 - f1: 0.6415 - val_loss: 0.5957 - val_accuracy: 0.7663 - val_f1: 0.3943
Epoch 2/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.4550 - accuracy: 0.8057 - f1: 0.7757 - val_loss: 0.5933 - val_accuracy: 0.7318 - val_f1: 0.4007
Epoch 3/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.3444 - accuracy: 0.8532 - f1: 0.8430 - val_loss: 0.5805 - val_accuracy: 0.7625 - val_f1: 0.4108
Epoch 4/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.2670 - accuracy: 0.8933 - f1: 0.8799 - val_loss: 0.6095 - val_accuracy: 0.7720 - val_f1: 0.3971
Epoch 5/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.2088 - accuracy: 0.9184 - f1: 0.9124 - val_loss: 0.7101 - val_accuracy: 0.7356 - val_f1: 0.4075
Epoch 6/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.1607 - accuracy: 0.9429 - f1: 0.9392 - val_loss: 0.7064 - val_accuracy: 0.7816 - val_f1: 0.4181
Epoch 7/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.1162 - accuracy: 0.9602 - f1: 0.9577 - val_loss: 0.8674 - val_accuracy: 0.7490 - val_f1: 0.3973
Epoch 8/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.0871 - accuracy: 0.9687 - f1: 0.9647 - val_loss: 0.8838 - val_accuracy: 0.7605 - val_f1: 0.4034
Epoch 9/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0584 - accuracy: 0.9834 - f1: 0.9822 - val_loss: 0.9486 - val_accuracy: 0.7701 - val_f1: 0.4158
Epoch 10/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0457 - accuracy: 0.9857 - f1: 0.9859 - val_loss: 1.1708 - val_accuracy: 0.7644 - val_f1: 0.3885
fold: 6
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 100us/step - loss: 0.8232 - accuracy: 0.6920 - f1: 0.6585 - val_loss: 0.7336 - val_accuracy: 0.7274 - val_f1: 0.3557
Epoch 2/10
4695/4695 [==============================] - 0s 37us/step - loss: 0.4436 - accuracy: 0.8062 - f1: 0.7857 - val_loss: 0.7280 - val_accuracy: 0.7543 - val_f1: 0.3867
Epoch 3/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.3374 - accuracy: 0.8560 - f1: 0.8389 - val_loss: 0.6861 - val_accuracy: 0.7351 - val_f1: 0.3902
Epoch 4/10
4695/4695 [==============================] - 0s 34us/step - loss: 0.2574 - accuracy: 0.8909 - f1: 0.8844 - val_loss: 0.7360 - val_accuracy: 0.7562 - val_f1: 0.4024
Epoch 5/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.1982 - accuracy: 0.9263 - f1: 0.9210 - val_loss: 0.8635 - val_accuracy: 0.7466 - val_f1: 0.3934
Epoch 6/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.1520 - accuracy: 0.9436 - f1: 0.9409 - val_loss: 0.9232 - val_accuracy: 0.7447 - val_f1: 0.3892
Epoch 7/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.1043 - accuracy: 0.9634 - f1: 0.9621 - val_loss: 1.0958 - val_accuracy: 0.7486 - val_f1: 0.3946
Epoch 8/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.0821 - accuracy: 0.9736 - f1: 0.9721 - val_loss: 1.1002 - val_accuracy: 0.7601 - val_f1: 0.4070
Epoch 9/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.0604 - accuracy: 0.9802 - f1: 0.9788 - val_loss: 1.1780 - val_accuracy: 0.7466 - val_f1: 0.4000
Epoch 10/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0421 - accuracy: 0.9891 - f1: 0.9882 - val_loss: 1.3750 - val_accuracy: 0.7754 - val_f1: 0.4184
fold: 7
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 71us/step - loss: 0.7600 - accuracy: 0.6980 - f1: 0.6550 - val_loss: 0.6631 - val_accuracy: 0.7198 - val_f1: 0.3790
Epoch 2/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.4402 - accuracy: 0.8098 - f1: 0.7893 - val_loss: 0.6068 - val_accuracy: 0.7447 - val_f1: 0.3815
Epoch 3/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.3343 - accuracy: 0.8588 - f1: 0.8420 - val_loss: 0.5843 - val_accuracy: 0.7639 - val_f1: 0.3957
Epoch 4/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.2518 - accuracy: 0.8956 - f1: 0.8861 - val_loss: 0.6626 - val_accuracy: 0.7678 - val_f1: 0.3999
Epoch 5/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.1949 - accuracy: 0.9265 - f1: 0.9218 - val_loss: 0.7474 - val_accuracy: 0.7639 - val_f1: 0.4044
Epoch 6/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.1392 - accuracy: 0.9512 - f1: 0.9488 - val_loss: 0.8605 - val_accuracy: 0.7543 - val_f1: 0.4018
Epoch 7/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.1003 - accuracy: 0.9661 - f1: 0.9662 - val_loss: 0.9123 - val_accuracy: 0.7505 - val_f1: 0.3944
Epoch 8/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0724 - accuracy: 0.9761 - f1: 0.9749 - val_loss: 1.0348 - val_accuracy: 0.7639 - val_f1: 0.4020
Epoch 9/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0548 - accuracy: 0.9834 - f1: 0.9820 - val_loss: 1.1090 - val_accuracy: 0.7505 - val_f1: 0.4015
Epoch 10/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0361 - accuracy: 0.9898 - f1: 0.9893 - val_loss: 1.2704 - val_accuracy: 0.7562 - val_f1: 0.4047
fold: 8
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 73us/step - loss: 0.7797 - accuracy: 0.6780 - f1: 0.6403 - val_loss: 0.5673 - val_accuracy: 0.7678 - val_f1: 0.3960
Epoch 2/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.4565 - accuracy: 0.8043 - f1: 0.7848 - val_loss: 0.5715 - val_accuracy: 0.7774 - val_f1: 0.3882
Epoch 3/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.3395 - accuracy: 0.8573 - f1: 0.8404 - val_loss: 0.5859 - val_accuracy: 0.7716 - val_f1: 0.3972
Epoch 4/10
4695/4695 [==============================] - 0s 35us/step - loss: 0.2674 - accuracy: 0.8952 - f1: 0.8868 - val_loss: 0.6052 - val_accuracy: 0.7505 - val_f1: 0.3903
Epoch 5/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.1998 - accuracy: 0.9250 - f1: 0.9198 - val_loss: 0.6822 - val_accuracy: 0.7601 - val_f1: 0.4069
Epoch 6/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.1456 - accuracy: 0.9470 - f1: 0.9445 - val_loss: 0.7537 - val_accuracy: 0.7447 - val_f1: 0.3979
Epoch 7/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.1079 - accuracy: 0.9629 - f1: 0.9614 - val_loss: 0.8431 - val_accuracy: 0.7601 - val_f1: 0.4052
Epoch 8/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0732 - accuracy: 0.9793 - f1: 0.9788 - val_loss: 1.1177 - val_accuracy: 0.7697 - val_f1: 0.3974
Epoch 9/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0531 - accuracy: 0.9832 - f1: 0.9828 - val_loss: 1.2543 - val_accuracy: 0.7697 - val_f1: 0.4002
Epoch 10/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0381 - accuracy: 0.9876 - f1: 0.9863 - val_loss: 1.2298 - val_accuracy: 0.7620 - val_f1: 0.4044
fold: 9
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 67us/step - loss: 0.7575 - accuracy: 0.7016 - f1: 0.6663 - val_loss: 0.5716 - val_accuracy: 0.7562 - val_f1: 0.3738
Epoch 2/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.4497 - accuracy: 0.8115 - f1: 0.7850 - val_loss: 0.5157 - val_accuracy: 0.7927 - val_f1: 0.4063
Epoch 3/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.3515 - accuracy: 0.8545 - f1: 0.8377 - val_loss: 0.4948 - val_accuracy: 0.7985 - val_f1: 0.4168
Epoch 4/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.2783 - accuracy: 0.8839 - f1: 0.8746 - val_loss: 0.5267 - val_accuracy: 0.7927 - val_f1: 0.4096
Epoch 5/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.2107 - accuracy: 0.9178 - f1: 0.9109 - val_loss: 0.5996 - val_accuracy: 0.7927 - val_f1: 0.4194
Epoch 6/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.1586 - accuracy: 0.9399 - f1: 0.9374 - val_loss: 0.6961 - val_accuracy: 0.7658 - val_f1: 0.4059
Epoch 7/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.1235 - accuracy: 0.9559 - f1: 0.9537 - val_loss: 0.7991 - val_accuracy: 0.7562 - val_f1: 0.4180
Epoch 8/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0948 - accuracy: 0.9687 - f1: 0.9662 - val_loss: 0.8513 - val_accuracy: 0.7927 - val_f1: 0.4208
Epoch 9/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0629 - accuracy: 0.9819 - f1: 0.9808 - val_loss: 0.9813 - val_accuracy: 0.7927 - val_f1: 0.4211
Epoch 10/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0500 - accuracy: 0.9827 - f1: 0.9816 - val_loss: 1.0139 - val_accuracy: 0.8081 - val_f1: 0.4244
fold: 10
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 67us/step - loss: 0.8112 - accuracy: 0.6914 - f1: 0.6481 - val_loss: 0.6078 - val_accuracy: 0.7236 - val_f1: 0.3965
Epoch 2/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.4724 - accuracy: 0.7917 - f1: 0.7637 - val_loss: 0.5849 - val_accuracy: 0.7562 - val_f1: 0.4089
Epoch 3/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.3556 - accuracy: 0.8439 - f1: 0.8267 - val_loss: 0.5234 - val_accuracy: 0.7889 - val_f1: 0.4155
Epoch 4/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.2849 - accuracy: 0.8792 - f1: 0.8719 - val_loss: 0.5264 - val_accuracy: 0.7927 - val_f1: 0.4130
Epoch 5/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.2195 - accuracy: 0.9131 - f1: 0.9062 - val_loss: 0.6182 - val_accuracy: 0.7812 - val_f1: 0.3985
Epoch 6/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.1659 - accuracy: 0.9408 - f1: 0.9365 - val_loss: 0.6016 - val_accuracy: 0.7774 - val_f1: 0.4178
Epoch 7/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.1216 - accuracy: 0.9595 - f1: 0.9570 - val_loss: 0.6748 - val_accuracy: 0.7754 - val_f1: 0.4211
Epoch 8/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0885 - accuracy: 0.9715 - f1: 0.9692 - val_loss: 0.7804 - val_accuracy: 0.7735 - val_f1: 0.4091
Epoch 9/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0661 - accuracy: 0.9796 - f1: 0.9784 - val_loss: 0.9218 - val_accuracy: 0.7697 - val_f1: 0.4041
Epoch 10/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0452 - accuracy: 0.9849 - f1: 0.9840 - val_loss: 1.0382 - val_accuracy: 0.7678 - val_f1: 0.4057
In [416]:
epochs = 10
w,h=10,20 #Reshape to 10*20
input_shape = (w, h, 1)

Data Expansion

Feature Standardization is not needed here since we have normalized our data already. ZCA Whitening is not necessary as well because we are using PCA. We keep random rorations to train our model to better handle images. Random shifts might not make any differences in our case. Also, we keep random flips to improve performance since we believe our images can be fliped. Random shifts might not make any differences in our case.

Reference

Brownlee, Jason. “Image Augmentation for Deep Learning With Keras.” Machine Learning Mastery, 12 Sept. 2019, https://machinelearningmastery.com/image-augmentation-deep-learning-keras/.

First simple CNN

In [417]:
from keras.models import Sequential
from keras.layers import Reshape
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from sklearn.metrics import f1_score
In [418]:
mlp = Sequential()
mlp.add( Dense(input_dim=train_pca_200[i].shape[1], units=100, activation='relu') )
mlp.add( Dense(units=50, activation='relu') )
mlp.add( Dense(units=50, activation='relu') )
mlp.add( Dense(CLASSES) )
mlp.add( Activation('softmax') )

mlp.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy',f1])
In [419]:
# make a CNN with conv layer and max pooling
cnn = Sequential()
cnn.add( Reshape((1,w,h), input_shape=(1,w*h)) ) 
cnn.add( Conv2D(filters=16, kernel_size= (2, 2), padding='same', input_shape=(1,w,h),
               data_format="channels_first") )
cnn.add( Activation('relu') )
cnn.add( MaxPooling2D(pool_size=(2, 2), data_format="channels_first") )
# add one layer on flattened output
cnn.add( Flatten() )
cnn.add( Dense(CLASSES) )
cnn.add( Activation('softmax') )

cnn.summary()

cnn.compile(loss='mean_squared_error',
      optimizer='rmsprop',
      metrics=['accuracy',f1])
Model: "sequential_87"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
reshape_16 (Reshape)         (None, 1, 10, 20)         0         
_________________________________________________________________
conv2d_44 (Conv2D)           (None, 16, 10, 20)        80        
_________________________________________________________________
activation_107 (Activation)  (None, 16, 10, 20)        0         
_________________________________________________________________
max_pooling2d_32 (MaxPooling (None, 16, 5, 10)         0         
_________________________________________________________________
flatten_22 (Flatten)         (None, 800)               0         
_________________________________________________________________
dense_294 (Dense)            (None, 3)                 2403      
_________________________________________________________________
activation_108 (Activation)  (None, 3)                 0         
=================================================================
Total params: 2,483
Trainable params: 2,483
Non-trainable params: 0
_________________________________________________________________
In [420]:
from sklearn import metrics as mt
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline

def compare_mlp_cnn(cnn, mlp, X_test, y_test):
    plt.figure(figsize=(15,5))
    if cnn is not None:
        yhat_cnn = np.argmax(cnn.predict(np.expand_dims(X_test, axis=1)), axis=1)
        f1_cnn = mt.f1_score(y_test,yhat_cnn,average='macro') #Using f1 score
        plt.subplot(1,2,1)
        cm = mt.confusion_matrix(y_test,yhat_cnn)
        cm = cm/np.sum(cm,axis=1)[:,np.newaxis]
        sns.heatmap(cm, annot=True, fmt='.2f')
        plt.title('CNN: '+str(f1_cnn))
    
    if mlp is not None:
        yhat_mlp = np.argmax(mlp.predict(X_test), axis=1)
        f1_mlp = mt.f1_score(y_test,yhat_mlp,average='macro') #Using f1 score
        plt.subplot(1,2,2)
        cm = mt.confusion_matrix(y_test,yhat_mlp)
        cm = cm/np.sum(cm,axis=1)[:,np.newaxis]
        sns.heatmap(cm,annot=True, fmt='.2f')
        plt.title('MLP: '+str(f1_mlp))
In [427]:
def contingency_column(cnn, X_test, y_test):
    yhat_cnn = np.argmax(cnn.predict(np.expand_dims(X_test, axis=1)), axis=1)
    return [yhat_cnn[i] == y_test[i] for i in range(len(y_test))]
In [428]:
def contingency_column_mlp(cnn, X_test, y_test):
    yhat_mlp = np.argmax(mlp.predict(X_test), axis=1)
    return [yhat_mlp[i] == y_test[i] for i in range(len(y_test))]
In [429]:
# Let's train the model 
cnn_history=[]
mlp_history=[]
history_first=[]
mlp_his = []

classifier_cnn_first = []
classifier_mlp_first = []
for i in range(10):
    print('Fold:' + str(i+1))
    #simple cnn
    # we need to exapnd the dimensions here to give the 
    # "channels" dimension expected by Keras
    history =  cnn.fit(np.expand_dims(train_pca_200[i], axis=1), y_train_ohe[i], 
               batch_size=32, epochs=epochs, 
               shuffle=True, verbose=0,
               validation_data=(np.expand_dims(test_pca_200[i], axis=1),y_test_ohe[i]))
    
    cnn_history.append(cnn)
    history_first.append(history)
    #mlp
    print('MLP')
    mlp_model = mlp.fit(train_pca_200[i], y_train_ohe[i], 
            batch_size=32, epochs=10, 
            shuffle=True, verbose=1,
           validation_data=(test_pca_200[i],y_test_ohe[i]))
    mlp_history.append(mlp)
    mlp_his.append(mlp_model)

    classifier_cnn_first.append(contingency_column(cnn_history[i], test_pca_200[i],y_test[i]))
    classifier_mlp_first.append(contingency_column_mlp(mlp_history[i], test_pca_200[i],y_test[i]))
    compare_mlp_cnn(cnn_history[i],mlp_history[i],test_pca_200[i],y_test[i])
Fold:1
MLP
Train on 4693 samples, validate on 523 samples
Epoch 1/10
4693/4693 [==============================] - 0s 38us/step - loss: 0.0318 - accuracy: 0.9923 - f1: 0.9922 - val_loss: 1.1940 - val_accuracy: 0.7820 - val_f1: 0.4443
Epoch 2/10
4693/4693 [==============================] - 0s 35us/step - loss: 0.0331 - accuracy: 0.9900 - f1: 0.9890 - val_loss: 1.1856 - val_accuracy: 0.8011 - val_f1: 0.4521
Epoch 3/10
4693/4693 [==============================] - 0s 31us/step - loss: 0.0225 - accuracy: 0.9921 - f1: 0.9913 - val_loss: 1.2782 - val_accuracy: 0.7878 - val_f1: 0.4428
Epoch 4/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.0175 - accuracy: 0.9947 - f1: 0.9945 - val_loss: 1.3695 - val_accuracy: 0.7973 - val_f1: 0.4537
Epoch 5/10
4693/4693 [==============================] - 0s 38us/step - loss: 0.0160 - accuracy: 0.9940 - f1: 0.9938 - val_loss: 1.3953 - val_accuracy: 0.7839 - val_f1: 0.4435
Epoch 6/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.0111 - accuracy: 0.9957 - f1: 0.9954 - val_loss: 1.5326 - val_accuracy: 0.7878 - val_f1: 0.4477
Epoch 7/10
4693/4693 [==============================] - 0s 32us/step - loss: 0.0122 - accuracy: 0.9960 - f1: 0.9956 - val_loss: 1.6904 - val_accuracy: 0.7916 - val_f1: 0.4493
Epoch 8/10
4693/4693 [==============================] - 0s 31us/step - loss: 0.0141 - accuracy: 0.9953 - f1: 0.9946 - val_loss: 1.8706 - val_accuracy: 0.7801 - val_f1: 0.4387
Epoch 9/10
4693/4693 [==============================] - 0s 37us/step - loss: 0.0121 - accuracy: 0.9968 - f1: 0.9964 - val_loss: 1.8759 - val_accuracy: 0.7782 - val_f1: 0.4465
Epoch 10/10
4693/4693 [==============================] - 0s 40us/step - loss: 0.0067 - accuracy: 0.9979 - f1: 0.9977 - val_loss: 1.9049 - val_accuracy: 0.7859 - val_f1: 0.4521
Fold:2
MLP
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.2685 - accuracy: 0.9446 - f1: 0.9421 - val_loss: 0.1603 - val_accuracy: 0.9502 - val_f1: 0.5375
Epoch 2/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.1053 - accuracy: 0.9723 - f1: 0.9713 - val_loss: 0.0856 - val_accuracy: 0.9693 - val_f1: 0.5487
Epoch 3/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0624 - accuracy: 0.9789 - f1: 0.9771 - val_loss: 0.1297 - val_accuracy: 0.9636 - val_f1: 0.5430
Epoch 4/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0381 - accuracy: 0.9874 - f1: 0.9866 - val_loss: 0.0981 - val_accuracy: 0.9655 - val_f1: 0.5456
Epoch 5/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0276 - accuracy: 0.9911 - f1: 0.9903 - val_loss: 0.1064 - val_accuracy: 0.9693 - val_f1: 0.5478
Epoch 6/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0184 - accuracy: 0.9930 - f1: 0.9926 - val_loss: 0.1194 - val_accuracy: 0.9655 - val_f1: 0.5467
Epoch 7/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0175 - accuracy: 0.9949 - f1: 0.9949 - val_loss: 0.1533 - val_accuracy: 0.9483 - val_f1: 0.5336
Epoch 8/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0181 - accuracy: 0.9951 - f1: 0.9947 - val_loss: 0.1827 - val_accuracy: 0.9444 - val_f1: 0.5328
Epoch 9/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.0133 - accuracy: 0.9960 - f1: 0.9959 - val_loss: 0.2289 - val_accuracy: 0.9444 - val_f1: 0.5310
Epoch 10/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.0102 - accuracy: 0.9977 - f1: 0.9973 - val_loss: 0.1880 - val_accuracy: 0.9598 - val_f1: 0.5419
Fold:3
MLP
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0778 - accuracy: 0.9781 - f1: 0.9764 - val_loss: 0.0607 - val_accuracy: 0.9789 - val_f1: 0.5929
Epoch 2/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0304 - accuracy: 0.9896 - f1: 0.9886 - val_loss: 0.0624 - val_accuracy: 0.9789 - val_f1: 0.5945
Epoch 3/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0214 - accuracy: 0.9938 - f1: 0.9934 - val_loss: 0.0380 - val_accuracy: 0.9847 - val_f1: 0.5967
Epoch 4/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0178 - accuracy: 0.9953 - f1: 0.9949 - val_loss: 0.2161 - val_accuracy: 0.9559 - val_f1: 0.5732
Epoch 5/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0139 - accuracy: 0.9960 - f1: 0.9955 - val_loss: 0.0591 - val_accuracy: 0.9789 - val_f1: 0.5921
Epoch 6/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0092 - accuracy: 0.9972 - f1: 0.9969 - val_loss: 0.0796 - val_accuracy: 0.9770 - val_f1: 0.5910
Epoch 7/10
4694/4694 [==============================] - 0s 37us/step - loss: 0.0052 - accuracy: 0.9983 - f1: 0.9983 - val_loss: 0.0550 - val_accuracy: 0.9828 - val_f1: 0.5947
Epoch 8/10
4694/4694 [==============================] - 0s 41us/step - loss: 0.0120 - accuracy: 0.9970 - f1: 0.9963 - val_loss: 0.0758 - val_accuracy: 0.9674 - val_f1: 0.5846
Epoch 9/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.0117 - accuracy: 0.9962 - f1: 0.9958 - val_loss: 0.0962 - val_accuracy: 0.9751 - val_f1: 0.5897
Epoch 10/10
4694/4694 [==============================] - 0s 39us/step - loss: 0.0103 - accuracy: 0.9964 - f1: 0.9963 - val_loss: 0.1519 - val_accuracy: 0.9674 - val_f1: 0.5850
Fold:4
MLP
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 36us/step - loss: 0.0433 - accuracy: 0.9881 - f1: 0.9875 - val_loss: 0.0459 - val_accuracy: 0.9885 - val_f1: 0.5814
Epoch 2/10
4694/4694 [==============================] - 0s 34us/step - loss: 0.0308 - accuracy: 0.9906 - f1: 0.9887 - val_loss: 0.0728 - val_accuracy: 0.9789 - val_f1: 0.5729
Epoch 3/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0096 - accuracy: 0.9974 - f1: 0.9971 - val_loss: 0.0509 - val_accuracy: 0.9847 - val_f1: 0.5771
Epoch 4/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0144 - accuracy: 0.9966 - f1: 0.9963 - val_loss: 0.0504 - val_accuracy: 0.9866 - val_f1: 0.5788
Epoch 5/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0110 - accuracy: 0.9964 - f1: 0.9962 - val_loss: 0.0199 - val_accuracy: 0.9866 - val_f1: 0.5782
Epoch 6/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0110 - accuracy: 0.9964 - f1: 0.9960 - val_loss: 0.0459 - val_accuracy: 0.9789 - val_f1: 0.5742
Epoch 7/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0050 - accuracy: 0.9983 - f1: 0.9984 - val_loss: 0.0333 - val_accuracy: 0.9885 - val_f1: 0.5796
Epoch 8/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0057 - accuracy: 0.9977 - f1: 0.9976 - val_loss: 0.0996 - val_accuracy: 0.9808 - val_f1: 0.5733
Epoch 9/10
4694/4694 [==============================] - 0s 32us/step - loss: 0.0104 - accuracy: 0.9962 - f1: 0.9961 - val_loss: 0.0627 - val_accuracy: 0.9828 - val_f1: 0.5771
Epoch 10/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0055 - accuracy: 0.9979 - f1: 0.9979 - val_loss: 0.0798 - val_accuracy: 0.9866 - val_f1: 0.5787
Fold:5
MLP
Train on 4694 samples, validate on 522 samples
Epoch 1/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0446 - accuracy: 0.9900 - f1: 0.9895 - val_loss: 0.0124 - val_accuracy: 0.9943 - val_f1: 0.5648
Epoch 2/10
4694/4694 [==============================] - 0s 35us/step - loss: 0.0258 - accuracy: 0.9921 - f1: 0.9911 - val_loss: 0.0307 - val_accuracy: 0.9885 - val_f1: 0.5599
Epoch 3/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0113 - accuracy: 0.9960 - f1: 0.9959 - val_loss: 0.0506 - val_accuracy: 0.9847 - val_f1: 0.5583
Epoch 4/10
4694/4694 [==============================] - 0s 30us/step - loss: 0.0164 - accuracy: 0.9953 - f1: 0.9950 - val_loss: 0.0347 - val_accuracy: 0.9904 - val_f1: 0.5630
Epoch 5/10
4694/4694 [==============================] - 0s 30us/step - loss: 0.0103 - accuracy: 0.9955 - f1: 0.9951 - val_loss: 0.0411 - val_accuracy: 0.9923 - val_f1: 0.5637
Epoch 6/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0084 - accuracy: 0.9983 - f1: 0.9983 - val_loss: 0.0623 - val_accuracy: 0.9828 - val_f1: 0.5543
Epoch 7/10
4694/4694 [==============================] - 0s 30us/step - loss: 0.0058 - accuracy: 0.9977 - f1: 0.9976 - val_loss: 0.0690 - val_accuracy: 0.9828 - val_f1: 0.5552
Epoch 8/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0045 - accuracy: 0.9991 - f1: 0.9989 - val_loss: 0.0617 - val_accuracy: 0.9866 - val_f1: 0.5580
Epoch 9/10
4694/4694 [==============================] - 0s 33us/step - loss: 0.0085 - accuracy: 0.9979 - f1: 0.9979 - val_loss: 0.0626 - val_accuracy: 0.9789 - val_f1: 0.5529
Epoch 10/10
4694/4694 [==============================] - 0s 31us/step - loss: 0.0110 - accuracy: 0.9979 - f1: 0.9978 - val_loss: 0.0627 - val_accuracy: 0.9789 - val_f1: 0.5546
Fold:6
MLP
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0332 - accuracy: 0.9911 - f1: 0.9894 - val_loss: 0.0139 - val_accuracy: 0.9962 - val_f1: 0.5655
Epoch 2/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.0162 - accuracy: 0.9953 - f1: 0.9951 - val_loss: 0.0178 - val_accuracy: 0.9942 - val_f1: 0.5663
Epoch 3/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0145 - accuracy: 0.9966 - f1: 0.9960 - val_loss: 0.0205 - val_accuracy: 0.9962 - val_f1: 0.5671
Epoch 4/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0114 - accuracy: 0.9966 - f1: 0.9962 - val_loss: 0.0030 - val_accuracy: 1.0000 - val_f1: 0.5686
Epoch 5/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0043 - accuracy: 0.9989 - f1: 0.9990 - val_loss: 0.0916 - val_accuracy: 0.9904 - val_f1: 0.5621
Epoch 6/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0106 - accuracy: 0.9966 - f1: 0.9964 - val_loss: 0.0181 - val_accuracy: 0.9962 - val_f1: 0.5680
Epoch 7/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0093 - accuracy: 0.9977 - f1: 0.9974 - val_loss: 0.1081 - val_accuracy: 0.9866 - val_f1: 0.5630
Epoch 8/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0095 - accuracy: 0.9972 - f1: 0.9971 - val_loss: 0.0332 - val_accuracy: 0.9962 - val_f1: 0.5667
Epoch 9/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0015 - accuracy: 0.9994 - f1: 0.9993 - val_loss: 0.0527 - val_accuracy: 0.9904 - val_f1: 0.5649
Epoch 10/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0057 - accuracy: 0.9987 - f1: 0.9987 - val_loss: 0.0396 - val_accuracy: 0.9866 - val_f1: 0.5614
Fold:7
MLP
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0295 - accuracy: 0.9923 - f1: 0.9917 - val_loss: 0.0057 - val_accuracy: 0.9981 - val_f1: 0.5487
Epoch 2/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0148 - accuracy: 0.9957 - f1: 0.9953 - val_loss: 0.0081 - val_accuracy: 0.9962 - val_f1: 0.5456
Epoch 3/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0096 - accuracy: 0.9977 - f1: 0.9975 - val_loss: 0.0150 - val_accuracy: 0.9962 - val_f1: 0.5435
Epoch 4/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0088 - accuracy: 0.9974 - f1: 0.9972 - val_loss: 0.0074 - val_accuracy: 0.9981 - val_f1: 0.5478
Epoch 5/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0031 - accuracy: 0.9989 - f1: 0.9990 - val_loss: 0.0046 - val_accuracy: 0.9981 - val_f1: 0.5487
Epoch 6/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0060 - accuracy: 0.9987 - f1: 0.9987 - val_loss: 0.0240 - val_accuracy: 0.9904 - val_f1: 0.5426
Epoch 7/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0079 - accuracy: 0.9979 - f1: 0.9977 - val_loss: 0.0252 - val_accuracy: 0.9923 - val_f1: 0.5441
Epoch 8/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0052 - accuracy: 0.9977 - f1: 0.9977 - val_loss: 0.0189 - val_accuracy: 0.9942 - val_f1: 0.5459
Epoch 9/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0061 - accuracy: 0.9972 - f1: 0.9972 - val_loss: 0.0805 - val_accuracy: 0.9827 - val_f1: 0.5332
Epoch 10/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0041 - accuracy: 0.9983 - f1: 0.9985 - val_loss: 0.0548 - val_accuracy: 0.9846 - val_f1: 0.5370
Fold:8
MLP
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0482 - accuracy: 0.9879 - f1: 0.9865 - val_loss: 0.0167 - val_accuracy: 0.9962 - val_f1: 0.5657
Epoch 2/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0091 - accuracy: 0.9970 - f1: 0.9966 - val_loss: 0.0150 - val_accuracy: 0.9942 - val_f1: 0.5655
Epoch 3/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0122 - accuracy: 0.9970 - f1: 0.9969 - val_loss: 0.0633 - val_accuracy: 0.9942 - val_f1: 0.5643
Epoch 4/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0139 - accuracy: 0.9960 - f1: 0.9953 - val_loss: 0.0631 - val_accuracy: 0.9846 - val_f1: 0.5575
Epoch 5/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0084 - accuracy: 0.9981 - f1: 0.9981 - val_loss: 0.0255 - val_accuracy: 0.9942 - val_f1: 0.5643
Epoch 6/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0063 - accuracy: 0.9979 - f1: 0.9976 - val_loss: 0.0319 - val_accuracy: 0.9923 - val_f1: 0.5605
Epoch 7/10
4695/4695 [==============================] - 0s 30us/step - loss: 0.0035 - accuracy: 0.9994 - f1: 0.9994 - val_loss: 0.0218 - val_accuracy: 0.9923 - val_f1: 0.5613
Epoch 8/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0042 - accuracy: 0.9987 - f1: 0.9985 - val_loss: 0.0361 - val_accuracy: 0.9942 - val_f1: 0.5652
Epoch 9/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0095 - accuracy: 0.9977 - f1: 0.9974 - val_loss: 0.0234 - val_accuracy: 0.9904 - val_f1: 0.5660
Epoch 10/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0122 - accuracy: 0.9962 - f1: 0.9961 - val_loss: 0.0491 - val_accuracy: 0.9904 - val_f1: 0.5604
Fold:9
MLP
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0199 - accuracy: 0.9942 - f1: 0.9941 - val_loss: 0.0102 - val_accuracy: 0.9942 - val_f1: 0.5608
Epoch 2/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0163 - accuracy: 0.9953 - f1: 0.9947 - val_loss: 0.0013 - val_accuracy: 1.0000 - val_f1: 0.5686
Epoch 3/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0106 - accuracy: 0.9968 - f1: 0.9968 - val_loss: 0.0103 - val_accuracy: 0.9981 - val_f1: 0.5672
Epoch 4/10
4695/4695 [==============================] - 0s 34us/step - loss: 0.0055 - accuracy: 0.9983 - f1: 0.9980 - val_loss: 0.0097 - val_accuracy: 0.9981 - val_f1: 0.5683
Epoch 5/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0044 - accuracy: 0.9989 - f1: 0.9988 - val_loss: 0.0130 - val_accuracy: 0.9962 - val_f1: 0.5649
Epoch 6/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0028 - accuracy: 0.9991 - f1: 0.9991 - val_loss: 0.0075 - val_accuracy: 0.9981 - val_f1: 0.5672
Epoch 7/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0036 - accuracy: 0.9989 - f1: 0.9989 - val_loss: 0.0460 - val_accuracy: 0.9904 - val_f1: 0.5648
Epoch 8/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0038 - accuracy: 0.9989 - f1: 0.9988 - val_loss: 0.0280 - val_accuracy: 0.9885 - val_f1: 0.5624
Epoch 9/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0105 - accuracy: 0.9972 - f1: 0.9972 - val_loss: 0.0364 - val_accuracy: 0.9885 - val_f1: 0.5617
Epoch 10/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0012 - accuracy: 0.9996 - f1: 0.9995 - val_loss: 0.0581 - val_accuracy: 0.9885 - val_f1: 0.5623
Fold:10
MLP
Train on 4695 samples, validate on 521 samples
Epoch 1/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0339 - accuracy: 0.9925 - f1: 0.9918 - val_loss: 0.0135 - val_accuracy: 0.9942 - val_f1: 0.5658
Epoch 2/10
4695/4695 [==============================] - 0s 36us/step - loss: 0.0194 - accuracy: 0.9960 - f1: 0.9955 - val_loss: 0.0175 - val_accuracy: 0.9962 - val_f1: 0.5631
Epoch 3/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0118 - accuracy: 0.9955 - f1: 0.9953 - val_loss: 0.0101 - val_accuracy: 0.9981 - val_f1: 0.5673
Epoch 4/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0076 - accuracy: 0.9985 - f1: 0.9986 - val_loss: 0.0285 - val_accuracy: 0.9942 - val_f1: 0.5651
Epoch 5/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0070 - accuracy: 0.9981 - f1: 0.9981 - val_loss: 0.0328 - val_accuracy: 0.9942 - val_f1: 0.5646
Epoch 6/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0033 - accuracy: 0.9994 - f1: 0.9993 - val_loss: 0.0149 - val_accuracy: 0.9942 - val_f1: 0.5647
Epoch 7/10
4695/4695 [==============================] - 0s 34us/step - loss: 0.0040 - accuracy: 0.9987 - f1: 0.9985 - val_loss: 0.0286 - val_accuracy: 0.9923 - val_f1: 0.5635
Epoch 8/10
4695/4695 [==============================] - 0s 33us/step - loss: 0.0064 - accuracy: 0.9983 - f1: 0.9982 - val_loss: 0.0440 - val_accuracy: 0.9942 - val_f1: 0.5649
Epoch 9/10
4695/4695 [==============================] - 0s 32us/step - loss: 0.0055 - accuracy: 0.9991 - f1: 0.9992 - val_loss: 0.0559 - val_accuracy: 0.9904 - val_f1: 0.5624
Epoch 10/10
4695/4695 [==============================] - 0s 31us/step - loss: 0.0067 - accuracy: 0.9977 - f1: 0.9976 - val_loss: 0.0134 - val_accuracy: 0.9942 - val_f1: 0.5657

From above we can see that our cnn1 model does not perform well for class 3, pneumonia virus, which has a much lower F1 score compared to mlp model.

In [430]:
history_first[0].history['val_f1']
Out[430]:
[0.39603638648986816,
 0.3976963460445404,
 0.42507076263427734,
 0.42045190930366516,
 0.4151526093482971,
 0.4195258915424347,
 0.40792495012283325,
 0.3799225091934204,
 0.41920235753059387,
 0.41273489594459534]
In [431]:
np.expand_dims(train_pca_200[0], axis=1).shape
Out[431]:
(4693, 1, 200)

Second CNN

In [432]:
%%time

# changes: 
#    1. increased kernel size
cnn2 = Sequential()
cnn2.add( Reshape((1,w,h), input_shape=(1,200)) )
cnn2.add( Conv2D(filters=16, kernel_size= (3, 3), 
                padding='same', input_shape=(1,w,h),
                data_format="channels_first") )
cnn2.add( Activation('relu') )
cnn2.add( MaxPooling2D(pool_size=(2, 2), data_format="channels_first") )
# add one layer on flattened output
cnn2.add( Flatten() )
cnn2.add( Dense(CLASSES, activation='softmax') )

# Let's train the model 
cnn2.compile(loss='mean_squared_error',
              optimizer='rmsprop',
              metrics=['accuracy',f1])
CPU times: user 112 ms, sys: 43.2 ms, total: 155 ms
Wall time: 177 ms
In [433]:
# we need to exapnd the dimensions here to give the 
#   "channels" dimension expected by Keras
cnn2_history = []
history_second = []
classifier_2 = []

for i in range(10):
    print("fold: " + str(i+1))
    history =  cnn2.fit(np.expand_dims(train_pca_200[i], axis=1), y_train_ohe[i], 
               batch_size=32, epochs=epochs, 
               shuffle=True, verbose=0,
               validation_data=(np.expand_dims(test_pca_200[i], axis=1),y_test_ohe[i]))
    cnn2_history.append(cnn2)
    history_second.append(history)
    
    classifier_2.append(contingency_column(cnn2_history[i], test_pca_200[i], y_test[i]))
    compare_mlp_cnn(cnn2_history[i],mlp_history[i],test_pca_200[i],y_test[i])
fold: 1
fold: 2
fold: 3
fold: 4
fold: 5
fold: 6
fold: 7
fold: 8
fold: 9
fold: 10

From above we can see that our cnn2 model does not perform well for class 3, pneumonia virus, which has a much lower F1 score compared to mlp model.

In [434]:
history_second[0].history['val_f1']
Out[434]:
[0.3713720440864563,
 0.42548319697380066,
 0.4241640567779541,
 0.3974648118019104,
 0.36863332986831665,
 0.4249395728111267,
 0.4182492792606354,
 0.3767850399017334,
 0.36451637744903564,
 0.43276458978652954]

Third CNN

In [435]:
%%time

# changes: 
#    1. increased kernel size
#    2. add another conv/pool layer 
#    3. increase filter_layer from 16 to 32
cnn3 = Sequential()
cnn3.add( Reshape((1,w,h), input_shape=(1,200)))

num_filt_layers = [32, 32] 
for num_filters in num_filt_layers:
    cnn3.add( Conv2D(filters=num_filters, 
                    kernel_size=(3,3), 
                    padding='same',data_format="channels_first") )
    cnn3.add( Activation('relu'))
    cnn3.add( MaxPooling2D(pool_size=(2, 2), data_format="channels_first") )
    

# add one layer on flattened output
cnn3.add( Flatten() )
cnn3.add( Dense(CLASSES) )
cnn3.add( Activation('softmax') )

# Let's train the model 
cnn3.compile(loss='mean_squared_error',
              optimizer='rmsprop',
              metrics=['accuracy',f1])
CPU times: user 122 ms, sys: 26.5 ms, total: 148 ms
Wall time: 179 ms
In [436]:
# we need to exapnd the dimensions here to give the 
#   "channels" dimension expected by Keras
cnn3_history = []
history_third = []
classifier_3 = []

for i in range(10):
    print("fold: " + str(i+1))
    history =  cnn3.fit(np.expand_dims(train_pca_200[i], axis=1), y_train_ohe[i], 
               batch_size=32, epochs=epochs, 
               shuffle=True, verbose=0,
               validation_data=(np.expand_dims(test_pca_200[i], axis=1),y_test_ohe[i]))
    cnn3_history.append(cnn3)
    history_third.append(history)
    classifier_3.append(contingency_column(cnn3_history[i], test_pca_200[i], y_test[i]))
    compare_mlp_cnn(cnn3_history[i],mlp_history[i],test_pca_200[i],y_test[i])
fold: 1
fold: 2
fold: 3
fold: 4
fold: 5
fold: 6
fold: 7
fold: 8
fold: 9
fold: 10

From above we can see that our cnn3 model performs equally well for all classes.

In [437]:
history_third[0].history['val_f1']
Out[437]:
[0.34694933891296387,
 0.4086058735847473,
 0.38811802864074707,
 0.40020719170570374,
 0.4150916635990143,
 0.4147535562515259,
 0.39099401235580444,
 0.343827486038208,
 0.41264405846595764,
 0.41969284415245056]

Fourth CNN

In [493]:
%%time

# changes: 
#    1. increased kernel size
#    2. add another conv/pool layer with increasing num filters from 32 to 48
#    3. add more layers once flattened
#    4. add regularization l2
cnn4 = Sequential()
cnn4.add( Reshape((1,w,h), input_shape=(1,200)) )

num_filt_layers = [48, 48]
for num_filters in num_filt_layers:
    cnn4.add( Conv2D(filters=num_filters, 
                    kernel_size=(3,3), 
                    padding='same',data_format="channels_first"))
    cnn4.add( Activation('relu'))
    cnn4.add( MaxPooling2D(pool_size=(2, 2), data_format="channels_first"))
    

# add one layer on flattened output
cnn4.add( Flatten() )
cnn4.add( Dense(100, kernel_regularizer = l2(0.001)))
cnn4.add( Activation('relu') )
cnn4.add( Dense(CLASSES, kernel_regularizer = l2(0.001)))
cnn4.add( Activation('softmax') )

# Let's train the model 
cnn4.compile(loss='mean_squared_error',
              optimizer='rmsprop',
              metrics=['accuracy',f1])
CPU times: user 150 ms, sys: 51.2 ms, total: 202 ms
Wall time: 247 ms
In [494]:
# we need to exapnd the dimensions here to give the 
#   "channels" dimension expected by Keras
cnn4_history = []
history_fourth = []
classifier_4 = []

for i in range(10):
    history =  cnn4.fit(np.expand_dims(train_pca_200[i], axis=1), y_train_ohe[i], 
               batch_size=32, epochs=epochs, 
               shuffle=True, verbose=0,
               validation_data=(np.expand_dims(test_pca_200[i], axis=1),y_test_ohe[i]))
    cnn4_history.append(cnn4)
    history_fourth.append(history)
    classifier_4.append(contingency_column(cnn4_history[i], test_pca_200[i], y_test[i]))
    compare_mlp_cnn(cnn4_history[i],mlp_history[i],test_pca_200[i],y_test[i])

From above we can see that our cnn4 model performs well for all the classes.

In [496]:
history_fourth[0].history['val_f1']
Out[496]:
[0.391178697347641,
 0.391316294670105,
 0.36063656210899353,
 0.4113733172416687,
 0.426849365234375,
 0.4404926598072052,
 0.4152337610721588,
 0.42303594946861267,
 0.4172334372997284,
 0.41718369722366333]

Using more advanced CNN

In [441]:
datagen = ImageDataGenerator(featurewise_center=False,
    samplewise_center=False,
    featurewise_std_normalization=False,
    samplewise_std_normalization=False,
    zca_whitening=False,
    rotation_range=5, # used, Int. Degree range for random rotations.
    width_shift_range=0.1, # used, Float (fraction of total width). Range for random horizontal shifts.
    height_shift_range=0.1, # used,  Float (fraction of total height). Range for random vertical shifts.
    shear_range=0., # Float. Shear Intensity (Shear angle in counter-clockwise direction as radians)
    zoom_range=0.,
    channel_shift_range=0.,
    fill_mode='nearest',
    cval=0.,
    horizontal_flip=True,
    vertical_flip=False,
    rescale=None)

train_pca_reshape=[]
test_pca_reshape=[]
datagen_history=[]

for i in range(10):
    train_pca_temp = train_pca_200[i].reshape(len(train_pca_200[i]),w,h,1)
    test_pca_temp = test_pca_200[i].reshape(len(test_pca_200[i]),w,h,1)

    datagen.fit(train_pca_temp)
    train_pca_reshape.append(train_pca_temp)
    test_pca_reshape.append(test_pca_temp)
    datagen_history.append(datagen)
for i in range(10):
    train_pca_temp = train_pca_200[i].reshape(len(train_pca_200[i]),w,h,1)
    test_pca_temp = test_pca_200[i].reshape(len(test_pca_200[i]),w,h,1)

    datagen.fit(train_pca_temp)
    train_pca_reshape.append(train_pca_temp)
    test_pca_reshape.append(test_pca_temp)
    datagen_history.append(datagen)
In [442]:
from sklearn import metrics as mt
from matplotlib import pyplot as plt
from skimage.io import imshow
import seaborn as sns
%matplotlib inline

def summarize_net(net, X_test, y_test, title_text=''):
    plt.figure(figsize=(15,5))
    yhat = np.argmax(net.predict(X_test), axis=1)
    f1 = mt.f1_score(y_test,yhat,average = "macro")
    cm = mt.confusion_matrix(y_test,yhat)
    cm = cm/np.sum(cm,axis=1)[:,np.newaxis]
    sns.heatmap(cm, annot=True, fmt='.2f')
    plt.title(title_text+'{:.4f}'.format(f1))

Advanced CNN1

In [443]:
%%time 

cnn = Sequential()

# let's start with an AlexNet style convolutional phase
cnn.add(Conv2D(filters=32,
                input_shape = (w,h,1),
                kernel_size=(3,3), 
                padding='same', 
                activation='relu', data_format="channels_last")) # more compact syntax

# no max pool before next conv layer!!
cnn.add(Conv2D(filters=64,
                kernel_size=(3,3), 
                padding='same', 
                activation='relu')) # more compact syntax
cnn.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))
    

# add one layer on flattened output
cnn.add(Dropout(0.25)) # add some dropout for regularization after conv layers
cnn.add(Flatten())
cnn.add(Dense(128, activation='relu'))
cnn.add(Dropout(0.5)) # add some dropout for regularization, again!
cnn.add(Dense(CLASSES, activation='softmax'))

# Let's train the model 
cnn.compile(loss='categorical_crossentropy', # 'categorical_crossentropy' 'mean_squared_error'
              optimizer='rmsprop', # 'adadelta' 'rmsprop'
              metrics=['accuracy',f1])
CPU times: user 542 ms, sys: 33.8 ms, total: 576 ms
Wall time: 168 ms
In [446]:
# the flow method yields batches of images indefinitely, with the given transformations
cnn_generator = []
history_cnn=[]

classifier_adv = []
for i in range(10):
    print("fold: " + str(i+1))
    history = cnn.fit_generator(datagen.flow(train_pca_reshape[i], y_train_ohe[i], batch_size=128), 
                   steps_per_epoch=int(len(train_pca_reshape[i])/128), # how many generators to go through per epoch
                   epochs=epochs, verbose=1,validation_data=(test_pca_reshape[i],y_test_ohe[i]),
                   callbacks=[EarlyStopping(monitor='val_loss', patience=2)])
                   
    history_cnn.append(history)
    #pred = np.round(np.argmax(cnn.predict(X_test[i]),axis=1))
    #c = f1_score(np.round(np.argmax(y_test_ohe[i],axis =1)), pred)
    cnn_generator.append(cnn)
    classifier_adv.append(contingency_column_mlp(cnn_generator[i], test_pca_200[i], y_test[i]))
    
fold: 1
Epoch 1/10
36/36 [==============================] - 2s 57ms/step - loss: 0.8586 - accuracy: 0.6094 - f1: 0.4729 - val_loss: 0.7636 - val_accuracy: 0.6750 - val_f1: 0.3397
Epoch 2/10
36/36 [==============================] - 2s 54ms/step - loss: 0.8571 - accuracy: 0.6142 - f1: 0.4719 - val_loss: 0.7386 - val_accuracy: 0.6807 - val_f1: 0.3622
Epoch 3/10
36/36 [==============================] - 2s 54ms/step - loss: 0.8508 - accuracy: 0.6230 - f1: 0.4726 - val_loss: 0.8263 - val_accuracy: 0.6291 - val_f1: 0.3180
Epoch 4/10
36/36 [==============================] - 2s 53ms/step - loss: 0.8490 - accuracy: 0.6140 - f1: 0.4808 - val_loss: 0.8210 - val_accuracy: 0.6252 - val_f1: 0.3089
fold: 2
Epoch 1/10
36/36 [==============================] - 2s 53ms/step - loss: 0.8400 - accuracy: 0.6180 - f1: 0.4818 - val_loss: 0.7146 - val_accuracy: 0.7011 - val_f1: 0.3646
Epoch 2/10
36/36 [==============================] - 2s 55ms/step - loss: 0.8418 - accuracy: 0.6200 - f1: 0.4871 - val_loss: 0.6740 - val_accuracy: 0.7261 - val_f1: 0.3831
Epoch 3/10
36/36 [==============================] - 2s 62ms/step - loss: 0.8412 - accuracy: 0.6084 - f1: 0.4868 - val_loss: 0.6686 - val_accuracy: 0.7203 - val_f1: 0.3729
Epoch 4/10
36/36 [==============================] - 2s 60ms/step - loss: 0.8390 - accuracy: 0.6183 - f1: 0.4812 - val_loss: 0.7158 - val_accuracy: 0.7050 - val_f1: 0.3898
Epoch 5/10
36/36 [==============================] - 2s 56ms/step - loss: 0.8168 - accuracy: 0.6294 - f1: 0.5108 - val_loss: 0.6483 - val_accuracy: 0.7337 - val_f1: 0.4003
Epoch 6/10
36/36 [==============================] - 2s 59ms/step - loss: 0.8223 - accuracy: 0.6253 - f1: 0.5069 - val_loss: 0.6685 - val_accuracy: 0.7203 - val_f1: 0.3745
Epoch 7/10
36/36 [==============================] - 2s 60ms/step - loss: 0.8154 - accuracy: 0.6291 - f1: 0.5051 - val_loss: 0.6841 - val_accuracy: 0.7184 - val_f1: 0.3782
fold: 3
Epoch 1/10
36/36 [==============================] - 2s 59ms/step - loss: 0.8258 - accuracy: 0.6277 - f1: 0.4970 - val_loss: 0.7182 - val_accuracy: 0.7031 - val_f1: 0.4119
Epoch 2/10
36/36 [==============================] - 2s 55ms/step - loss: 0.8151 - accuracy: 0.6275 - f1: 0.5029 - val_loss: 0.7115 - val_accuracy: 0.7146 - val_f1: 0.4352
Epoch 3/10
36/36 [==============================] - 2s 58ms/step - loss: 0.8089 - accuracy: 0.6310 - f1: 0.5059 - val_loss: 0.7017 - val_accuracy: 0.7203 - val_f1: 0.4399
Epoch 4/10
36/36 [==============================] - 2s 59ms/step - loss: 0.8040 - accuracy: 0.6393 - f1: 0.5171 - val_loss: 0.6761 - val_accuracy: 0.7146 - val_f1: 0.4588
Epoch 5/10
36/36 [==============================] - 2s 66ms/step - loss: 0.7976 - accuracy: 0.6353 - f1: 0.5225 - val_loss: 0.6959 - val_accuracy: 0.7241 - val_f1: 0.4431
Epoch 6/10
36/36 [==============================] - 2s 61ms/step - loss: 0.8025 - accuracy: 0.6402 - f1: 0.5261 - val_loss: 0.6664 - val_accuracy: 0.7241 - val_f1: 0.4267
Epoch 7/10
36/36 [==============================] - 2s 61ms/step - loss: 0.7957 - accuracy: 0.6399 - f1: 0.5330 - val_loss: 0.6668 - val_accuracy: 0.7241 - val_f1: 0.4183
Epoch 8/10
36/36 [==============================] - 2s 61ms/step - loss: 0.7905 - accuracy: 0.6428 - f1: 0.5287 - val_loss: 0.7016 - val_accuracy: 0.7146 - val_f1: 0.4168
fold: 4
Epoch 1/10
36/36 [==============================] - 2s 58ms/step - loss: 0.8093 - accuracy: 0.6345 - f1: 0.5205 - val_loss: 0.6545 - val_accuracy: 0.7261 - val_f1: 0.3861
Epoch 2/10
36/36 [==============================] - 2s 56ms/step - loss: 0.8000 - accuracy: 0.6360 - f1: 0.5288 - val_loss: 0.6585 - val_accuracy: 0.7280 - val_f1: 0.3815
Epoch 3/10
36/36 [==============================] - 2s 57ms/step - loss: 0.7863 - accuracy: 0.6435 - f1: 0.5431 - val_loss: 0.6713 - val_accuracy: 0.7241 - val_f1: 0.3947
fold: 5
Epoch 1/10
36/36 [==============================] - 2s 57ms/step - loss: 0.7903 - accuracy: 0.6452 - f1: 0.5387 - val_loss: 0.6422 - val_accuracy: 0.7299 - val_f1: 0.3304
Epoch 2/10
36/36 [==============================] - 2s 60ms/step - loss: 0.7911 - accuracy: 0.6555 - f1: 0.5423 - val_loss: 0.6473 - val_accuracy: 0.7184 - val_f1: 0.3407
Epoch 3/10
36/36 [==============================] - 2s 58ms/step - loss: 0.7944 - accuracy: 0.6476 - f1: 0.5401 - val_loss: 0.6790 - val_accuracy: 0.7222 - val_f1: 0.3025
fold: 6
Epoch 1/10
36/36 [==============================] - 2s 57ms/step - loss: 0.7894 - accuracy: 0.6549 - f1: 0.5478 - val_loss: 0.6550 - val_accuracy: 0.7006 - val_f1: 0.3641
Epoch 2/10
36/36 [==============================] - 2s 61ms/step - loss: 0.7868 - accuracy: 0.6488 - f1: 0.5456 - val_loss: 0.7826 - val_accuracy: 0.6430 - val_f1: 0.3323
Epoch 3/10
36/36 [==============================] - 2s 62ms/step - loss: 0.8059 - accuracy: 0.6374 - f1: 0.5207 - val_loss: 0.6819 - val_accuracy: 0.7006 - val_f1: 0.3589
fold: 7
Epoch 1/10
36/36 [==============================] - 2s 62ms/step - loss: 0.7805 - accuracy: 0.6540 - f1: 0.5569 - val_loss: 0.7099 - val_accuracy: 0.6891 - val_f1: 0.3900
Epoch 2/10
36/36 [==============================] - 2s 58ms/step - loss: 0.7788 - accuracy: 0.6457 - f1: 0.5408 - val_loss: 0.7049 - val_accuracy: 0.7044 - val_f1: 0.3463
Epoch 3/10
36/36 [==============================] - 2s 60ms/step - loss: 0.7780 - accuracy: 0.6534 - f1: 0.5475 - val_loss: 0.6992 - val_accuracy: 0.7025 - val_f1: 0.3491
Epoch 4/10
36/36 [==============================] - 2s 58ms/step - loss: 0.7772 - accuracy: 0.6483 - f1: 0.5504 - val_loss: 0.6428 - val_accuracy: 0.7236 - val_f1: 0.3601
Epoch 5/10
36/36 [==============================] - 2s 58ms/step - loss: 0.7648 - accuracy: 0.6481 - f1: 0.5375 - val_loss: 0.6344 - val_accuracy: 0.7217 - val_f1: 0.3694
Epoch 6/10
36/36 [==============================] - 2s 58ms/step - loss: 0.7799 - accuracy: 0.6464 - f1: 0.5469 - val_loss: 0.6481 - val_accuracy: 0.7140 - val_f1: 0.3573
Epoch 7/10
36/36 [==============================] - 2s 57ms/step - loss: 0.7809 - accuracy: 0.6455 - f1: 0.5494 - val_loss: 0.6784 - val_accuracy: 0.7102 - val_f1: 0.3511
fold: 8
Epoch 1/10
36/36 [==============================] - 2s 56ms/step - loss: 0.7850 - accuracy: 0.6516 - f1: 0.5469 - val_loss: 0.6124 - val_accuracy: 0.7582 - val_f1: 0.4016
Epoch 2/10
36/36 [==============================] - 2s 60ms/step - loss: 0.7800 - accuracy: 0.6545 - f1: 0.5553 - val_loss: 0.6141 - val_accuracy: 0.7524 - val_f1: 0.4048
Epoch 3/10
36/36 [==============================] - 2s 59ms/step - loss: 0.7856 - accuracy: 0.6573 - f1: 0.5470 - val_loss: 0.6639 - val_accuracy: 0.7370 - val_f1: 0.3882
fold: 9
Epoch 1/10
36/36 [==============================] - 2s 65ms/step - loss: 0.7776 - accuracy: 0.6578 - f1: 0.5649 - val_loss: 0.6041 - val_accuracy: 0.7255 - val_f1: 0.3677
Epoch 2/10
36/36 [==============================] - 2s 60ms/step - loss: 0.7801 - accuracy: 0.6497 - f1: 0.5425 - val_loss: 0.6220 - val_accuracy: 0.7294 - val_f1: 0.3768
Epoch 3/10
36/36 [==============================] - 2s 55ms/step - loss: 0.7721 - accuracy: 0.6519 - f1: 0.5507 - val_loss: 0.6080 - val_accuracy: 0.7466 - val_f1: 0.3516
fold: 10
Epoch 1/10
36/36 [==============================] - 2s 54ms/step - loss: 0.7640 - accuracy: 0.6589 - f1: 0.5621 - val_loss: 0.6378 - val_accuracy: 0.7486 - val_f1: 0.4218
Epoch 2/10
36/36 [==============================] - 2s 53ms/step - loss: 0.7659 - accuracy: 0.6551 - f1: 0.5414 - val_loss: 0.6502 - val_accuracy: 0.7543 - val_f1: 0.3832
Epoch 3/10
36/36 [==============================] - 2s 57ms/step - loss: 0.7733 - accuracy: 0.6514 - f1: 0.5481 - val_loss: 0.6630 - val_accuracy: 0.7409 - val_f1: 0.3828
In [447]:
for i in range(10):
    summarize_net(cnn_generator[i], test_pca_reshape[i], y_test[i], title_text='Using Expansion:')

From above we can see that our advanced cnn1 model performs bad for class 3, pneumonia virus, which has a F1 score around 0.3.

Advanced CNN2

In [448]:
#Use the Validation Data
from keras.callbacks import EarlyStopping
from keras.regularizers import l2 
l2_lambda = 0.0001

# Use Kaiming He to regularize ReLU layers: https://arxiv.org/pdf/1502.01852.pdf
# Use Glorot/Bengio for linear/sigmoid/softmax: http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf 
cnn = Sequential()

cnn.add(Conv2D(filters=32,
               input_shape = (w,h,1),
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu',
               data_format="channels_last")) # more compact syntax

cnn.add(Conv2D(filters=32,
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu',data_format="channels_last"))
cnn.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))

cnn.add(Conv2D(filters=64,
               input_shape = (w,h,1),
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu',data_format="channels_last")) # more compact syntax

cnn.add(Conv2D(filters=64,
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu'))
cnn.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_last"))

cnn.add(Conv2D(filters=128,
               input_shape = (w,h,1),
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu',data_format="channels_last")) # more compact syntax

cnn.add(Conv2D(filters=128,
               kernel_size=(3,3),
               kernel_initializer='he_uniform', 
               kernel_regularizer=l2(l2_lambda),
               padding='same', 
               activation='relu',data_format="channels_last"))
    

# add one layer on flattened output

cnn.add(Flatten())
cnn.add(Dropout(0.25)) # add some dropout for regularization after conv layers
cnn.add(Dense(128, 
              activation='relu',
              kernel_initializer='he_uniform',
              kernel_regularizer=l2(l2_lambda)
       ))
cnn.add(Dropout(0.5)) # add some dropout for regularization, again!
cnn.add(Dense(CLASSES, 
              activation='softmax', 
              kernel_initializer='glorot_uniform',
              kernel_regularizer=l2(l2_lambda)
             ))

# Let's train the model 
cnn.compile(loss='categorical_crossentropy', # 'categorical_crossentropy' 'mean_squared_error'
              optimizer='rmsprop', # 'adadelta' 'rmsprop'
              metrics=['accuracy',f1])
In [449]:
# the flow method yields batches of images indefinitely, with the given transformations
cnn_generator_2 = []
history_cnn_2=[]
classifier_adv2 = []

for i in range(10):
    print("fold: " + str(i+1))
    history = cnn.fit_generator(datagen.flow(train_pca_reshape[i], y_train_ohe[i], batch_size=128), 
                   steps_per_epoch=int(len(train_pca_reshape[i])/128), # how many generators to go through per epoch
                   epochs=epochs, verbose=1,validation_data=(test_pca_reshape[i],y_test_ohe[i]),
                   callbacks=[EarlyStopping(monitor='val_loss', patience=2)])
    history_cnn_2.append(history)
    #pred = np.round(np.argmax(cnn.predict(X_test[i]),axis=1))
    #c = accuracy_score(np.round(np.argmax(y_test_ohe[i],axis =1)), pred)
    cnn_generator_2.append(cnn)
    classifier_adv2.append(contingency_column_mlp(cnn_generator_2[i], test_pca_200[i], y_test[i]))
fold: 1
Epoch 1/10
36/36 [==============================] - 3s 94ms/step - loss: 2.3218 - accuracy: 0.4390 - f1: 0.1486 - val_loss: 1.1277 - val_accuracy: 0.4857 - val_f1: 0.1109
Epoch 2/10
36/36 [==============================] - 4s 115ms/step - loss: 1.1801 - accuracy: 0.4629 - f1: 0.1244 - val_loss: 1.1037 - val_accuracy: 0.5392 - val_f1: 0.0823
Epoch 3/10
36/36 [==============================] - 4s 113ms/step - loss: 1.1597 - accuracy: 0.4784 - f1: 0.1270 - val_loss: 1.0480 - val_accuracy: 0.6042 - val_f1: 0.1693
Epoch 4/10
36/36 [==============================] - 4s 122ms/step - loss: 1.1388 - accuracy: 0.4957 - f1: 0.1727 - val_loss: 1.0141 - val_accuracy: 0.5870 - val_f1: 0.2166
Epoch 5/10
36/36 [==============================] - 4s 118ms/step - loss: 1.0921 - accuracy: 0.5400 - f1: 0.2480 - val_loss: 1.1174 - val_accuracy: 0.4971 - val_f1: 0.1642
Epoch 6/10
36/36 [==============================] - 3s 93ms/step - loss: 1.0886 - accuracy: 0.5266 - f1: 0.2434 - val_loss: 0.9842 - val_accuracy: 0.6214 - val_f1: 0.2610
Epoch 7/10
36/36 [==============================] - 4s 97ms/step - loss: 1.0620 - accuracy: 0.5549 - f1: 0.3166 - val_loss: 0.9327 - val_accuracy: 0.6463 - val_f1: 0.2894
Epoch 8/10
36/36 [==============================] - 3s 89ms/step - loss: 1.0412 - accuracy: 0.5590 - f1: 0.3394 - val_loss: 0.9092 - val_accuracy: 0.6558 - val_f1: 0.3012
Epoch 9/10
36/36 [==============================] - 3s 89ms/step - loss: 1.0260 - accuracy: 0.5770 - f1: 0.3734 - val_loss: 0.9375 - val_accuracy: 0.6616 - val_f1: 0.2680
Epoch 10/10
36/36 [==============================] - 4s 100ms/step - loss: 1.0093 - accuracy: 0.5744 - f1: 0.3787 - val_loss: 0.9087 - val_accuracy: 0.6577 - val_f1: 0.3302
fold: 2
Epoch 1/10
36/36 [==============================] - 3s 89ms/step - loss: 1.0082 - accuracy: 0.5747 - f1: 0.3815 - val_loss: 0.8801 - val_accuracy: 0.6782 - val_f1: 0.3267
Epoch 2/10
36/36 [==============================] - 4s 107ms/step - loss: 0.9794 - accuracy: 0.5867 - f1: 0.4159 - val_loss: 0.9079 - val_accuracy: 0.6628 - val_f1: 0.3095
Epoch 3/10
36/36 [==============================] - 5s 130ms/step - loss: 0.9824 - accuracy: 0.5918 - f1: 0.4217 - val_loss: 0.9009 - val_accuracy: 0.6552 - val_f1: 0.3228
fold: 3
Epoch 1/10
36/36 [==============================] - 4s 115ms/step - loss: 0.9632 - accuracy: 0.5937 - f1: 0.4303 - val_loss: 0.9418 - val_accuracy: 0.6590 - val_f1: 0.3385
Epoch 2/10
36/36 [==============================] - 4s 106ms/step - loss: 0.9601 - accuracy: 0.5968 - f1: 0.4351 - val_loss: 0.8348 - val_accuracy: 0.6935 - val_f1: 0.3420
Epoch 3/10
36/36 [==============================] - 4s 101ms/step - loss: 0.9516 - accuracy: 0.5994 - f1: 0.4497 - val_loss: 0.9039 - val_accuracy: 0.6533 - val_f1: 0.3323
Epoch 4/10
36/36 [==============================] - 3s 87ms/step - loss: 0.9398 - accuracy: 0.6039 - f1: 0.4621 - val_loss: 1.0134 - val_accuracy: 0.5843 - val_f1: 0.2952
fold: 4
Epoch 1/10
36/36 [==============================] - 3s 87ms/step - loss: 0.9356 - accuracy: 0.6032 - f1: 0.4658 - val_loss: 0.8047 - val_accuracy: 0.6858 - val_f1: 0.3310
Epoch 2/10
36/36 [==============================] - 3s 91ms/step - loss: 0.9358 - accuracy: 0.6110 - f1: 0.4709 - val_loss: 0.8219 - val_accuracy: 0.6820 - val_f1: 0.3458
Epoch 3/10
36/36 [==============================] - 3s 89ms/step - loss: 0.9226 - accuracy: 0.6196 - f1: 0.4792 - val_loss: 0.7930 - val_accuracy: 0.7088 - val_f1: 0.3773
Epoch 4/10
36/36 [==============================] - 3s 93ms/step - loss: 0.9301 - accuracy: 0.6130 - f1: 0.4826 - val_loss: 0.8542 - val_accuracy: 0.6705 - val_f1: 0.3177
Epoch 5/10
36/36 [==============================] - 3s 96ms/step - loss: 0.8931 - accuracy: 0.6297 - f1: 0.5028 - val_loss: 0.7908 - val_accuracy: 0.6935 - val_f1: 0.3659
Epoch 6/10
36/36 [==============================] - 3s 90ms/step - loss: 0.8970 - accuracy: 0.6272 - f1: 0.5041 - val_loss: 0.8150 - val_accuracy: 0.6801 - val_f1: 0.3541
Epoch 7/10
36/36 [==============================] - 3s 87ms/step - loss: 0.8911 - accuracy: 0.6275 - f1: 0.5111 - val_loss: 0.8341 - val_accuracy: 0.6686 - val_f1: 0.3556
fold: 5
Epoch 1/10
36/36 [==============================] - 3s 93ms/step - loss: 0.9094 - accuracy: 0.6191 - f1: 0.4984 - val_loss: 0.7785 - val_accuracy: 0.6877 - val_f1: 0.3560
Epoch 2/10
36/36 [==============================] - 3s 91ms/step - loss: 0.9023 - accuracy: 0.6299 - f1: 0.4996 - val_loss: 0.7435 - val_accuracy: 0.7011 - val_f1: 0.3485
Epoch 3/10
36/36 [==============================] - 3s 89ms/step - loss: 0.8994 - accuracy: 0.6237 - f1: 0.4928 - val_loss: 0.7886 - val_accuracy: 0.6743 - val_f1: 0.3213
Epoch 4/10
36/36 [==============================] - 3s 93ms/step - loss: 0.8820 - accuracy: 0.6356 - f1: 0.5070 - val_loss: 0.8166 - val_accuracy: 0.6858 - val_f1: 0.3318
fold: 6
Epoch 1/10
36/36 [==============================] - 4s 98ms/step - loss: 0.8794 - accuracy: 0.6346 - f1: 0.5211 - val_loss: 0.8526 - val_accuracy: 0.6775 - val_f1: 0.3347
Epoch 2/10
36/36 [==============================] - 3s 88ms/step - loss: 0.8817 - accuracy: 0.6293 - f1: 0.5062 - val_loss: 0.8995 - val_accuracy: 0.6372 - val_f1: 0.3344
Epoch 3/10
36/36 [==============================] - 3s 89ms/step - loss: 0.8708 - accuracy: 0.6400 - f1: 0.5224 - val_loss: 0.7946 - val_accuracy: 0.6718 - val_f1: 0.3430
Epoch 4/10
36/36 [==============================] - 3s 89ms/step - loss: 0.8691 - accuracy: 0.6385 - f1: 0.5318 - val_loss: 0.7617 - val_accuracy: 0.6948 - val_f1: 0.3340
Epoch 5/10
36/36 [==============================] - 3s 70ms/step - loss: 0.8543 - accuracy: 0.6490 - f1: 0.5238 - val_loss: 0.8658 - val_accuracy: 0.6449 - val_f1: 0.3233
Epoch 6/10
36/36 [==============================] - 3s 89ms/step - loss: 0.8567 - accuracy: 0.6394 - f1: 0.5316 - val_loss: 1.0068 - val_accuracy: 0.6200 - val_f1: 0.3427
fold: 7
Epoch 1/10
36/36 [==============================] - 3s 88ms/step - loss: 0.8668 - accuracy: 0.6420 - f1: 0.5222 - val_loss: 0.7323 - val_accuracy: 0.7025 - val_f1: 0.4120
Epoch 2/10
36/36 [==============================] - 3s 77ms/step - loss: 0.8608 - accuracy: 0.6418 - f1: 0.5318 - val_loss: 0.7549 - val_accuracy: 0.7025 - val_f1: 0.3503
Epoch 3/10
36/36 [==============================] - 3s 78ms/step - loss: 0.8604 - accuracy: 0.6416 - f1: 0.5278 - val_loss: 0.7632 - val_accuracy: 0.7083 - val_f1: 0.3635
fold: 8
Epoch 1/10
36/36 [==============================] - 3s 76ms/step - loss: 0.8501 - accuracy: 0.6501 - f1: 0.5431 - val_loss: 0.7657 - val_accuracy: 0.7025 - val_f1: 0.3646
Epoch 2/10
36/36 [==============================] - 3s 77ms/step - loss: 0.8424 - accuracy: 0.6564 - f1: 0.5526 - val_loss: 0.7585 - val_accuracy: 0.6967 - val_f1: 0.3714
Epoch 3/10
36/36 [==============================] - 3s 77ms/step - loss: 0.8376 - accuracy: 0.6427 - f1: 0.5384 - val_loss: 0.7569 - val_accuracy: 0.7198 - val_f1: 0.3434
Epoch 4/10
36/36 [==============================] - 3s 74ms/step - loss: 0.8555 - accuracy: 0.6475 - f1: 0.5336 - val_loss: 0.8425 - val_accuracy: 0.6871 - val_f1: 0.3711
Epoch 5/10
36/36 [==============================] - 3s 74ms/step - loss: 0.8507 - accuracy: 0.6442 - f1: 0.5376 - val_loss: 0.8971 - val_accuracy: 0.6583 - val_f1: 0.3448
fold: 9
Epoch 1/10
36/36 [==============================] - 3s 77ms/step - loss: 0.8450 - accuracy: 0.6462 - f1: 0.5425 - val_loss: 0.7279 - val_accuracy: 0.6891 - val_f1: 0.3322
Epoch 2/10
36/36 [==============================] - 3s 76ms/step - loss: 0.8546 - accuracy: 0.6437 - f1: 0.5364 - val_loss: 0.8118 - val_accuracy: 0.6622 - val_f1: 0.3129
Epoch 3/10
36/36 [==============================] - 3s 80ms/step - loss: 0.8367 - accuracy: 0.6569 - f1: 0.5370 - val_loss: 0.7396 - val_accuracy: 0.6910 - val_f1: 0.3709
fold: 10
Epoch 1/10
36/36 [==============================] - 3s 80ms/step - loss: 0.8289 - accuracy: 0.6593 - f1: 0.5540 - val_loss: 0.7358 - val_accuracy: 0.6967 - val_f1: 0.2989
Epoch 2/10
36/36 [==============================] - 3s 79ms/step - loss: 0.8204 - accuracy: 0.6510 - f1: 0.5458 - val_loss: 0.7103 - val_accuracy: 0.7274 - val_f1: 0.3817
Epoch 3/10
36/36 [==============================] - 3s 84ms/step - loss: 0.8291 - accuracy: 0.6562 - f1: 0.5613 - val_loss: 0.7153 - val_accuracy: 0.7217 - val_f1: 0.3742
Epoch 4/10
36/36 [==============================] - 3s 80ms/step - loss: 0.8183 - accuracy: 0.6552 - f1: 0.5585 - val_loss: 0.7179 - val_accuracy: 0.7255 - val_f1: 0.3735
In [450]:
for i in range(10):
    summarize_net(cnn_generator_2[i], test_pca_reshape[i], y_test[i], title_text='Using Exp.+Reg.+Init.:')

From above we can see that our advanced cnn2 model performs bad for class 3, pneumonia virus, which has a F1 score as low as 0.2.

Compare Performance of the Training and Validation sets

In [451]:
%matplotlib inline
for i in range(10):
    legends=['MLP','Simple CNN1','Simple CNN2','Simple CNN3','Simple CNN4','CNN Advanced 1','CNN Advanced 2']
    plt.figure(figsize=(20,60))
    plt.subplot(10,2,1)
    plt.plot(mlp_his[i].history['f1'])
    plt.plot(history_first[i].history['f1'])
    plt.plot(history_second[i].history['f1'])
    plt.plot(history_third[i].history['f1'])
    plt.plot(history_fourth[i].history['f1'])
    plt.plot(history_cnn[i].history['f1'])
    plt.plot(history_cnn_2[i].history['f1'])
    plt.legend(legends)
    plt.xlabel('epochs')
    plt.ylabel('f1_score %')
    plt.title('Training')
    plt.subplot(10,2,2)
    plt.plot(mlp_his[i].history['val_f1'])
    plt.plot(history_first[i].history['val_f1'])
    plt.plot(history_second[i].history['val_f1'])
    plt.plot(history_third[i].history['val_f1'])
    plt.plot(history_fourth[i].history['val_f1'])
    plt.plot(history_cnn[i].history['val_f1'])
    plt.plot(history_cnn_2[i].history['val_f1'])
    plt.legend(legends)
    plt.xlabel('epochs')
    plt.ylabel('val_f1_score %')
    plt.title('Validation')

MLP performs best compared to all the cnn models for both training and validation set. Our F1 score for validation set is much lower than the training set for all our models. But according to the validation F1 score using sklearn, we do not see the same magnitude of the decrease. We are unsure why this is happening because our model trains very well on the test set and then it performs poorly on the validation set. This means that our model must be overtraining somehow. We also l2 regularization and drop out to prevent overfitting problem but it does not make a difference.If we adapted the parameters some more, we may have found a way to prevent this overtraining.

In [452]:
Methods = ['MLP','Simple CNN1','Simple CNN2','Simple CNN3','Simple CNN4','CNN Advanced 1','CNN Advanced 2']

print('| {:^8} | {:^15} | {:^21}| {:^21} '.format('fold','Method','f1','validate f1'))
print('| {:^8} | {:^15} | {:^21}| {:^21} '.format('', '', '', '', ''))

for i in range(10):
    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[0],np.mean(mlp_his[i].history['f1']),np.mean(mlp_his[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[1],np.mean(history_first[i].history['f1']),np.mean(history_first[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[2],np.mean(history_second[i].history['f1']),np.mean(history_second[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[3],np.mean(history_third[i].history['f1']),np.mean(history_third[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[4],np.mean(history_fourth[i].history['f1']),np.mean(history_fourth[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[5],np.mean(history_cnn[i].history['f1']),np.mean(history_cnn[i].history['val_f1'])))

    print('| {:^8} | {:^15} | {:^21}| {:^21}  '.format(i+1,Methods[6],np.mean(history_cnn_2[i].history['f1']),np.mean(history_cnn_2[i].history['val_f1'])))
|   fold   |     Method      |          f1          |      validate f1      
|          |                 |                      |                       
|    1     |       MLP       |  0.9940503239631653  |  0.4470693439245224    
|    1     |   Simple CNN1   |  0.7825987339019775  |  0.4093718618154526    
|    1     |   Simple CNN2   |  0.7216504216194153  |  0.4004372298717499    
|    1     |   Simple CNN3   |  0.7519026398658752  |  0.39408840537071227   
|    1     |   Simple CNN4   |  0.7653467059135437  |  0.4132735162973404    
|    1     | CNN Advanced 1  |  0.4745631217956543  |   0.332185797393322    
|    1     | CNN Advanced 2  |  0.24722325801849365 |  0.21931340247392656   
|    2     |       MLP       |  0.9842848777770996  |  0.5408697187900543    
|    2     |   Simple CNN1   |   0.791621744632721  |  0.4265595316886902    
|    2     |   Simple CNN2   |  0.7851310968399048  |  0.4027851313352585    
|    2     |   Simple CNN3   |  0.8856533169746399  |  0.45093384981155393   
|    2     |   Simple CNN4   |  0.9050347208976746  |  0.4751848101615906    
|    2     | CNN Advanced 1  |  0.4942280650138855  |  0.3804930405957358    
|    2     | CNN Advanced 2  |  0.4063750207424164  |   0.319683700799942    
|    3     |       MLP       |  0.9932171702384949  |  0.5894550621509552    
|    3     |   Simple CNN1   |  0.8025477528572083  |  0.46002690494060516   
|    3     |   Simple CNN2   |  0.8067962527275085  |  0.45557706654071806   
|    3     |   Simple CNN3   |  0.9343255162239075  |  0.5317069470882416    
|    3     |   Simple CNN4   |  0.9409934878349304  |  0.5593414187431336    
|    3     | CNN Advanced 1  |  0.5166633129119873  |  0.4313242770731449    
|    3     | CNN Advanced 2  |  0.44426628947257996 |  0.32700764387845993   
|    4     |       MLP       |  0.9951826333999634  |   0.57713303565979     
|    4     |   Simple CNN1   |  0.8147581219673157  |  0.4509463101625443    
|    4     |   Simple CNN2   |  0.8285732269287109  |   0.440309551358223    
|    4     |   Simple CNN3   |  0.9593132734298706  |  0.5289987742900848    
|    4     |   Simple CNN4   |  0.9601665735244751  |   0.542474901676178    
|    4     | CNN Advanced 1  |  0.5308073163032532  |  0.38742531339327496   
|    4     | CNN Advanced 2  |  0.4880906641483307  |  0.34963653343064444   
|    5     |       MLP       |  0.9956989288330078  |  0.5584729135036468    
|    5     |   Simple CNN1   |  0.8246275186538696  |  0.42763361632823943   
|    5     |   Simple CNN2   |  0.8395110964775085  |  0.4291463166475296    
|    5     |   Simple CNN3   |  0.9675599932670593  |  0.5231164664030075    
|    5     |   Simple CNN4   |  0.9656192064285278  |  0.5389614343643189    
|    5     | CNN Advanced 1  |  0.5403542518615723  |  0.3245311776796977    
|    5     | CNN Advanced 2  |  0.49945488572120667 |   0.339429572224617    
|    6     |       MLP       |  0.9964660406112671  |  0.5653589129447937    
|    6     |   Simple CNN1   |  0.8353769183158875  |  0.4300306439399719    
|    6     |   Simple CNN2   |  0.8456352353096008  |   0.442216694355011    
|    6     |   Simple CNN3   |  0.9723480343818665  |  0.5281442403793335    
|    6     |   Simple CNN4   |  0.9675102233886719  |  0.5291293203830719    
|    6     | CNN Advanced 1  |   0.538063108921051  |  0.3517395257949829    
|    6     | CNN Advanced 2  |  0.5228201746940613  |  0.3353409518798192    
|    7     |       MLP       |  0.9970451593399048  |  0.5437064170837402    
|    7     |   Simple CNN1   |  0.8365464210510254  |  0.4238510519266129    
|    7     |   Simple CNN2   |  0.8447054624557495  |  0.4472626745700836    
|    7     |   Simple CNN3   |  0.9725138545036316  |  0.5240674257278443    
|    7     |   Simple CNN4   |   0.967964768409729  |  0.5274586200714111    
|    7     | CNN Advanced 1  |  0.5470613241195679  |  0.3604816666671208    
|    7     | CNN Advanced 2  |  0.5272718667984009  |  0.37523799141248065   
|    8     |       MLP       |  0.9962480664253235  |  0.5630600690841675    
|    8     |   Simple CNN1   |  0.8399603962898254  |  0.43967682123184204   
|    8     |   Simple CNN2   |  0.8545953035354614  |  0.43395075500011443   
|    8     |   Simple CNN3   |  0.9745408296585083  |  0.5376389503479004    
|    8     |   Simple CNN4   |  0.9702730178833008  |  0.5408569872379303    
|    8     | CNN Advanced 1  |  0.5497516989707947  |  0.39821969469388324   
|    8     | CNN Advanced 2  |  0.5410593152046204  |  0.35905401706695556   
|    9     |       MLP       |   0.997592568397522  |  0.5648285746574402    
|    9     |   Simple CNN1   |  0.8424159288406372  |  0.4506095081567764    
|    9     |   Simple CNN2   |  0.8582040667533875  |  0.44016813635826113   
|    9     |   Simple CNN3   |  0.9758592844009399  |  0.5546473979949951    
|    9     |   Simple CNN4   |  0.9724848866462708  |  0.5547329246997833    
|    9     | CNN Advanced 1  |  0.5526972413063049  |  0.36536018053690594   
|    9     | CNN Advanced 2  |   0.538645327091217  |  0.33865243196487427   
|    10    |       MLP       |  0.9971911311149597  |  0.5647027432918549    
|    10    |   Simple CNN1   |  0.8460994958877563  |  0.45338704288005827   
|    10    |   Simple CNN2   |  0.8586812019348145  |  0.46615504622459414   
|    10    |   Simple CNN3   |  0.9755724668502808  |  0.5469811081886291    
|    10    |   Simple CNN4   |  0.9738162755966187  |  0.5500017464160919    
|    10    | CNN Advanced 1  |  0.5505291819572449  |  0.39595308899879456   
|    10    | CNN Advanced 2  |  0.5549203157424927  |  0.3570657968521118    

Mcnemara's Test

In statistics, McNemar's test is a statistical test used on paired nominal data. It is applied to 2 × 2 contingency tables with a dichotomous trait, with matched pairs of subjects, to determine whether the row and column marginal frequencies are equal (that is, whether there is "marginal homogeneity")

The test is applied to a 2 × 2 contingency table, which tabulates the outcomes of two tests on a sample of n subjects, as follows.

</h2>

Test 2 positive Test 2 negative Rowtotal
Test 1 positive a b a+b
Test 1 negative c d c+d
Column total a+c b+d n

The null hypothesis of marginal homogeneity states that the two marginal probabilities for each outcome are the same, i.e. \begin{aligned}~p_{a}+p_{b}=p_{b} + p_{c}~and~p_{c} + p_{d}=p_{b} + p_{d}\end{aligned}

Thus the null and alternative hypotheses are[1]

\begin{aligned}H_{0}&:~p_{b}=p_{c}\\H_{1}&:~p_{b}\neq p_{c}\end{aligned}

Here $p_{a}$, etc., denote the theoretical probability of occurrences in cells with the corresponding label.

The McNemar test statistic is: \begin{aligned}{\chi^2} = \frac{(b-c)^2}{b-c}\end{aligned}

Under the null hypothesis, with a sufficiently large number of discordants (cells b and c), $\chi^2$ has a chi-squared distribution with 1 degree of freedom. If the $\chi^2$ result is significant, this provides sufficient evidence to reject the null hypothesis, in favour of the alternative hypothesis that $p_{b} ≠ p_{c}$, which would mean that the marginal proportions are significantly different from each other.

Reference

“McNemar's Test.” Wikipedia, Wikimedia Foundation, 22 Nov. 2019, https://en.wikipedia.org/wiki/McNemar's_test.

In [473]:
def make_contingency_table(classifier_1, classifier_2):
    '''
    input: classifier 1 right or wrong, classifier 2 right or wrong
    '''
    table = [[0, 0],[0,0]]
    for k_fold in range(len(classifier_1)):
        for i in range(len(classifier_1)):
            if classifier_1[k_fold][i]:
                i = 0
            else:
                i = 1
            if classifier_2[k_fold][i]:
                j = 0
            else:
                j = 1
            table[i][j] += 1
    return table
In [454]:
# Code taken form https://machinelearningmastery.com/mcnemars-test-for-machine-learning/

# Example of calculating the mcnemar test
from statsmodels.stats.contingency_tables import mcnemar
# define contingency table
table = [[4, 2], [2,4]]
def print_mcnemar(table):         
    # calculate mcnemar test
    result = mcnemar(table, exact=True)
    # summarize the finding
    print('statistic=%.3f, p-value=%.3f' % (result.statistic, result.pvalue))
    # interpret the p-value
    alpha = 0.05
    if result.pvalue > alpha:
        print('Same proportions of errors (fail to reject H0)')
    else:
        print('Different proportions of errors (reject H0)')

print_mcnemar(table)
statistic=2.000, p-value=1.000
Same proportions of errors (fail to reject H0)
In [455]:
# Example of calculating the mcnemar test
from statsmodels.stats.contingency_tables import mcnemar
# define contingency table
table = [[4, 2], [2,4]]
In [457]:
print_mcnemar(make_contingency_table(classifier_cnn_first, classifier_mlp_first))
statistic=0.000, p-value=0.000
Different proportions of errors (reject H0)

Compare Simple Models

In [458]:
print_mcnemar(make_contingency_table(classifier_cnn_first, classifier_2))
statistic=2.000, p-value=0.000
Different proportions of errors (reject H0)
In [459]:
print_mcnemar(make_contingency_table(classifier_cnn_first, classifier_3))
statistic=5.000, p-value=0.000
Different proportions of errors (reject H0)
In [477]:
print_mcnemar(make_contingency_table(classifier_cnn_first, classifier_4))
statistic=0.000, p-value=0.000
Different proportions of errors (reject H0)
In [460]:
print_mcnemar(make_contingency_table(classifier_2, classifier_3))
statistic=0.000, p-value=0.001
Different proportions of errors (reject H0)
In [463]:
print_mcnemar(make_contingency_table(classifier_2, classifier_4))
statistic=0.000, p-value=0.001
Different proportions of errors (reject H0)
In [462]:
print_mcnemar(make_contingency_table(classifier_3, classifier_4))
statistic=0.000, p-value=0.016
Different proportions of errors (reject H0)

Based on the results above, we find that all the simple cnn models have different proportions of errors,which means they are significantly different from each other, and we will find out the best one later.

Compare Advanced Models

In [461]:
print_mcnemar(make_contingency_table(classifier_adv, classifier_adv2))
statistic=0.000, p-value=1.000
Same proportions of errors (fail to reject H0)

Based on the results above, we find that the two advanced cnn models are the same, so we can use either of them.

Summary

Based on the results above, we find that all the simple cnn models have different proportions of errors, but the two advanced models have same proportions of errors. Now we check which cnn model is best below.

Our Best CNN Model

In [465]:
#Find the best model with highest validate_f1:  (Using the average of validate f1)
avgcnn1_f1 = [] #Simple cnn1
avgcnn2_f1 = [] #Simple cnn2
avgcnn3_f1 = [] #Simple cnn3
avgcnn4_f1 = [] #Simple cnn4
avgcnn5_f1 = [] #Advanced cnn1
avgcnn6_f1 = [] #Advanced cnn2

for i in range(10):
    avgcnn1_f1.append(np.mean(history_first[i].history['val_f1']))
    avgcnn2_f1.append(np.mean(history_second[i].history['val_f1']))
    avgcnn3_f1.append(np.mean(history_third[i].history['val_f1']))
    avgcnn4_f1.append(np.mean(history_fourth[i].history['val_f1']))
    avgcnn5_f1.append(np.mean(history_cnn[i].history['val_f1']))
    avgcnn6_f1.append(np.mean(history_cnn_2[i].history['val_f1']))
    
first_cnn = np.mean(avgcnn1_f1)
second_cnn = np.mean(avgcnn2_f1)    
third_cnn = np.mean(avgcnn3_f1)
fourth_cnn = np.mean(avgcnn4_f1)
adv_cnn1 = np.mean(avgcnn5_f1)
adv_cnn2 = np.mean(avgcnn6_f1)
    
f1_val = [first_cnn,second_cnn,third_cnn,fourth_cnn,adv_cnn1,adv_cnn2]
f1_val_name =['Simple CNN1','Simple CNN2','Simple CNN3','Simple CNN4','CNN Advanced 1','CNN Advanced 2']

max_f1 = first_cnn 
for idx, score in enumerate(f1_val):
    if  score > max_f1:
        max_f1 = score
        method = f1_val_name[idx]


print(' Our best model is : ' + str(method), "\n", 
      "Validate f1 :" + str(max_f1))
    
 Our best model is : Simple CNN4 
 Validate f1 :0.5231415680050849

Our best model is Simple CNN4 with the highest validate f1 score.

Compare our best model with MLP

In [467]:
#Compare our best model Simple cnn4 with mlp
avgmlp_f1 = []
for i in range(10):
    avgmlp_f1.append(np.mean(mlp_his[i].history['val_f1']))

    
plt.plot(avgmlp_f1)
plt.plot(avgcnn4_f1)
plt.legend(['MLP','Simple CNN4'])
plt.ylabel('val_f1_score %')
plt.xlabel('epochs')
plt.title('Comparison Validation Score')
Out[467]:
Text(0.5, 1.0, 'Comparison Validation Score')

ROC Curve

Micro- and macro-averages will compute slightly different things, and thus their interpretation differs. A macro-average will compute the metric independently for each class and then take the average (hence treating all classes equally), whereas a micro-average will aggregate the contributions of all classes to compute the average metric. In a multi-class classification setup, micro-average is preferable since there might be class imbalance (we have many more examples of one class than of other classes).

Reference

“Computing AUC and ROC Curve from Multi-Class Data in Scikit-Learn (Sklearn)?” Stack Overflow, 1 Jan. 1966, https://stackoverflow.com/questions/33547965/computing-auc-and-roc-curve-from-multi-class-data-in-scikit-learn-sklearn.

Contributor, Guest. “Understanding ROC Curves with Python.” Stack Abuse, Stack Abuse, 25 Feb. 2019, https://stackabuse.com/understanding-roc-curves-with-python/.

First, we just check each class' ROC performance.

In [468]:
def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element
In [475]:
#Modified by https://stackoverflow.com/questions/33547965/computing-auc-and-roc-curve-from-multi-class-data-in-scikit-learn-sklearn
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from scipy import interp
for j in range(10):
    print("Fold:" + str(j+1))
    y_pred = cnn4.predict(np.expand_dims(test_pca_200[j], axis=1))
    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    mean_roc = 0
    for i in range(CLASSES):
        fpr[i], tpr[i], _ = roc_curve(y_test_ohe[j][:, i], y_pred[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])
        mean_roc += roc_auc[i]
    mean_roc = mean_roc/CLASSES
    
    colors = cycle(['blue', 'red', 'green'])
    for i, color in zip(range(CLASSES), colors):
        plt.plot(fpr[i], tpr[i], color=color, lw=2,linestyle=':',
             label='ROC curve of CNN4 class {0} (area = {1:0.4f})'
             ''.format(i, roc_auc[i]))
    
    y_pred_mlp = mlp.predict(test_pca_200[j]) 
    fpr_mlp = dict()
    tpr_mlp = dict()
    roc_auc_mlp = dict()
    mean_roc_mlp = 0
    for i in range(CLASSES):
        fpr_mlp[i], tpr_mlp[i], _ = roc_curve(y_test_ohe[j][:, i], y_pred_mlp[:, i])
        roc_auc_mlp[i] = auc(fpr_mlp[i], tpr_mlp[i])
        mean_roc_mlp += roc_auc_mlp[i]
    mean_roc_mlp = mean_roc_mlp/CLASSES
        
        
    colors_mlp = cycle(['deeppink', 'chartreuse', '#FFDD44'])
    for i, color in zip(range(CLASSES), colors_mlp):
        plt.plot(fpr_mlp[i], tpr_mlp[i], color=color, lw=2, linestyle='-.',
             label='ROC curve of MLP class {0} (area = {1:0.4f})'
             ''.format(i, roc_auc_mlp[i]))

    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([-0.05, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic to multi-class')
    plt.legend(loc="lower right")
    plt.show()
    
    print("The average ROC for CNN is:" ,mean_roc)
    print("The average ROC for MLP is:" ,mean_roc_mlp)
Fold:1
The average ROC for CNN is: 0.9801448294388679
The average ROC for MLP is: 1.0
Fold:2
The average ROC for CNN is: 0.9857191058944421
The average ROC for MLP is: 1.0
Fold:3
The average ROC for CNN is: 0.9920703059008318
The average ROC for MLP is: 1.0
Fold:4
The average ROC for CNN is: 0.9823457907224981
The average ROC for MLP is: 0.9999887219488987
Fold:5
The average ROC for CNN is: 0.9924948822680997
The average ROC for MLP is: 0.9999823417530268
Fold:6
The average ROC for CNN is: 0.977205540151679
The average ROC for MLP is: 0.9999773121198352
Fold:7
The average ROC for CNN is: 0.9939696859433363
The average ROC for MLP is: 1.0
Fold:8
The average ROC for CNN is: 0.9868232958645407
The average ROC for MLP is: 1.0
Fold:9
The average ROC for CNN is: 0.9916471634738239
The average ROC for MLP is: 1.0
Fold:10
The average ROC for CNN is: 0.9881292463238648
The average ROC for MLP is: 0.9999773121198351
In [476]:
#Modified by https://stackoverflow.com/questions/33547965/computing-auc-and-roc-curve-from-multi-class-data-in-scikit-learn-sklearn
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from scipy import interp
for j in range(10):
    print("Fold:" + str(j+1))
    y_pred = cnn4.predict(np.expand_dims(test_pca_200[j], axis=1))
    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    for i in range(CLASSES):
        fpr[i], tpr[i], _ = roc_curve(y_test_ohe[j][:, i], y_pred[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])
        
    # Compute micro-average ROC curve and ROC area       
    fpr["micro"], tpr["micro"], _ = roc_curve(y_test_ohe[j].ravel(), y_pred.ravel())
    roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
    
    y_pred_mlp = mlp.predict(test_pca_200[j]) 
    fpr_mlp = dict()
    tpr_mlp = dict()
    roc_auc_mlp = dict()
    for i in range(CLASSES):
        fpr_mlp[i], tpr_mlp[i], _ = roc_curve(y_test_ohe[j][:, i], y_pred_mlp[:, i])
        roc_auc_mlp[i] = auc(fpr_mlp[i], tpr_mlp[i])
        
    # Compute micro-average ROC curve and ROC area       
    fpr_mlp["micro"], tpr_mlp["micro"], _ = roc_curve(y_test_ohe[j].ravel(), y_pred_mlp.ravel())
    roc_auc_mlp["micro"] = auc(fpr_mlp["micro"], tpr_mlp["micro"])
           
    # Plot all ROC curves
    plt.figure()
    plt.plot(fpr["micro"], tpr["micro"],
         label='micro-average ROC curve CNN4 (area = {0:0.4f})'
               ''.format(roc_auc["micro"]),
         color='deeppink', linestyle=':', linewidth=2)
    plt.plot(fpr_mlp["micro"], tpr_mlp["micro"],
         label='micro-average ROC curve MLP (area = {0:0.4f})'
               ''.format(roc_auc_mlp["micro"]),
         color='navy', linestyle=':', linewidth=2)
    
    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([-0.05, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver operating characteristic to multi-class')
    plt.legend(loc="lower right")
    plt.show()
Fold:1
Fold:2
Fold:3
Fold:4
Fold:5
Fold:6
Fold:7
Fold:8
Fold:9
Fold:10

Conclusion

Based on the ROC result, the MLP model performs the best,but our Simple CNN4 also performs well.

Turned in Early so no Extra Work

In [ ]:
 
In [ ]: